Mysql num rows ошибка

mysql_num_rows() expects parameter 1 to be resource, but you gave it a string. You should make a query and obtain the resource returned by mysql_query().

For example:

$resource = mysql_query($login);
$rows = mysql_num_rows($resource);

To use the mysql_* functions, you would do something like this:

mysql_connect('host', 'user', 'password'); // connect to server
mysql_select_db('database name'); // select the database you'll be working with

$result = mysql_query('SELECT test FROM test_table'); // make a query
while ($row = mysql_fetch_assoc($result)) { // go through the obtained results
    echo $row['test']; // use the obtained results
}

mysql_close(); // close the database connection

If you want to use sprintf() to compose the query, I suggest you create the string and store it in an appropriately named variable, to make things easier to follow:

$query = sprintf("SELECT test FROM test_table WHERE a = '%s' AND b = '%s'",
    mysql_real_escape_string($a),
    mysql_real_escape_string($b));

Then send the query to mysql_query() to perform it:

$result = mysql_query($query);

Also note that the $link parameter is optional. If all you ever do in that script is work with a single database connection, you may omit it to make the code clearer.


As a side note, it’s bad practice to obtain the number of rows returned by a query with mysql_num_rows() if you don’t need the data as well. If all you need to find out is how many rows there are, consider using SELECT COUNT(*) AS total ... instead, then get the value of total with mysql_fetch_assoc().


And last but not least, do consider using PDO instead of the mysql_* functions, as it will likely help you in the long run. Check out this tutorial to find out how to use it.

EDIT: Complete rewrite

Try this:

<?php



$host = "host";
$user = "user";
$password = "password";
$database = "database";


$username = 'jack'; /* Insert $_Post [''] here with username variable you pass. You could sanitize and validate with for example filter_var (), clean (), etc */
$password_user = 'password from jack'; // same here.

$link = mysqli_connect($host, $user, $password, $database);
        IF (!$link){
        echo ("Unable to connect to database!");
        }

        ELSE{
$query = "SELECT * FROM account WHERE username ='$username' AND password = md5('$password_user')";
            $result = mysqli_query($link, $query);
            $num_rows = mysqli_num_rows($result);
            $row = mysqli_fetch_array($result, MYSQLI_BOTH);

            // COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE

            if ($row) {
                    session_start();
                    $_SESSION['login'] = "1"; // pleae not that 1 is converted into a string value
                    $_SESSION['username'] = $username; // added username, just to test.
                    header ("Location: page1.php");
                }   
                    else {
                        $error_message = "Login failed.  Please try again.";
                        echo $error_message;
                    }
            // CLOSE CONNECTION
            mysqli_close($link);            
        }
?>

Sample data:

CREATE TABLE account (
  id INT auto_increment primary key,
  username VARCHAR(30),
  password VARCHAR(50)
  );


INSERT INTO account(username, password)
VALUES 
("bob", md5('password from bob')), 
("jack", md5('password from jack')), 
('joe', md5('password from joe'));

SQL FIDDLE DEMO

Sample page1

<?php
session_start();
$login = $_SESSION['login'];
$username = $_SESSION['username'];

echo '<h1>It WORKS, <i>'.$username.'</i>!!!</h1>';


?>

Important to note is that I have used the MYSQLI library instead of the MYSQL library. If you have more than one column in you table you should select your output per column. For example, $result['id'].

I found that you didn’t escape variable in and out in you SQL statement. I have to note that I didn’t debug the part below COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS. I think you can manage that on your own.

W.R.T. the santization and validation you have to do some more work. I don’t know how you data is past via the user login in form. Let say you will use POST. In that case you can start at the top of you page with first retrieving all the posted variable using $_POST. Then filter them to make sure you code in is not open for SQL injection. E.g. $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);

После перехода с денвера(php 5.3) на xamp(php 5.5) появилась ошибка. Как ее исправить?
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:xampphtdocsErudituslistNotes.php on line 10

$result5 = mysql_query("SELECT id,text,date FROM notes WHERE userid='$idPol' AND activ='0' ORDER BY date DESC",$db);
if(mysql_num_rows($result5) > 0){
    echo("1");
}else{
    echo("0");
}


  • Вопрос задан

    более трёх лет назад

  • 15051 просмотр

Выведите:

echo mysql_error($db);

давайте глянем что там :)

Скорее всего ошибка еще до выборки, т.е. в подключении.

Может даже ругаться на зарезервированное слово date тогда возьмите его как `date`

Пригласить эксперта

Используйте mysqli или PDO.
mysql_* уже давно депрекейтед.

Разобрался, показало что таблица не существует. Как оказалось я просто перепутал две буквы в названии таблице)) что касается PDO это то то понятно, но переписывать весь сайт на PDO пока нет времени(


  • Показать ещё
    Загружается…

22 июн. 2023, в 00:59

8000 руб./за проект

22 июн. 2023, в 00:56

8000 руб./за проект

22 июн. 2023, в 00:39

12000 руб./за проект

Минуточку внимания

$sql = "SELECT id, title, date, text, author, author_email FROM column_text WHERE id='$id'";
$result = mysql_query($sql);
$number = mysql_num_rows($result);
echo "<BR>число рядов = $number";
if (!$number==1) {
print "error!";exit;
}
$id = mysql_result($result,0,"id");
$subject = mysql_result($result,0,"title");
$date = mysql_result($result,0,"date");
$text = mysql_result($result,0,"text");
$author = mysql_result($result,0,"author");
$author_email = mysql_result($result,0,"author_email");
$text = nl2br($text);
echo "<br>Автор: <a href=mailto:$author_email>$author</a><BR>$date<br><b>$title</b><br>$text";

Let’s first grasp the definition of mysqli_num_rows before going on to the actual reason and possible solution for the current problem. It will assist us in identifying where we are making errors, particularly for beginners.

Syntax

mysqli_num_rows ($resultSet);

Input param:: $resultSet is a required parameter.
Return: Total number of rows in resultSet.

Based on the definition we are required to pass resultset returned from mysqli_query or other similar result set retrieval functions as arguments.

Now let’s take a look at the technique below for a step-by-step guide and see how we can fix mysqli_num_rows expects parameter 1 warning with code examples.


  • Why does getting mysqli_num_rows() expect parameter 1 to be mysqli_result, boolean given, and how to fix it?
  • Why does the mysqli_num_rows function return an unexpected count?
  • Feedback: Your input is valuable to us. Please provide feedback on this article.

Here we are reproducing errors for demonstration purposes. Let’s go through the following code and understand the reason.

<?php
$host = "localhost"; // Specify your server Host/IP address
$uname = "uname"; // Replace your Database username here
$pwd = "password"; // Replace your Database password here
$db= "demo"; //Replace your database name here

$mysqli = new mysqli($host,$uname,$pwd,$db);

// Check connection
if ($mysqli -> connect_errno) {
  echo "Failed to connect Database: " . $mysqli -> connect_error;
  exit();
}

$resultSet = mysqli_query($mysqli, "SELECT name, email FROM tbl_notExist");

var_dump($resultSet); 

var_dump(mysqli_num_rows($resultSet));
Result: 
bool(false) 

NULL

Warning : PHP Warning:  mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

Explanation:

  • Here we are trying to execute a query against a non-existing database table. Therefore as the table does not exist mysqli_query returns a false boolean value.
  • But as per definitions described above it required the result set as input param but false given and so it raised a warning.
  • Therefore in most cases, we have an issue in the query specified which is wrong and requires fixing the query.

What if rewrite above program using the correct table

$resultSet = mysqli_query($mysqli, "SELECT name, email FROM tbl_employee");

var_dump($resultSet);

var_dump(mysqli_num_rows($resultSet));
 

Result: 
object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(2) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) }

1
 

Explanation:
As we can see mysqli_query returns mysqli_result reference with correct query and returns a count of rows returned as 1.

There can be common reasons behind this problem. Would like to highlight again the definition mysqli num rows function that returns rows counts from the result set of a specified MySQL query.

Therefore if we perform any MySQL Aggregate Functions query such as count., AVG(), min, max, etc will return one single row meaning that the result set contains only one record and hence num rows functions return 1 in such cases.

It is recommended to run a specified query using any MySQL Tools such as phpMyAdmin, MySQL Workbench, HeidiSQL, and others to make sure the query is correct and verify the number of records returned by it.

Yes, it was beneficial.

Yes, it was helpful, however more information is required.

It wasn’t helpful, so no.

Feedback (optional) Please provide additional details about the selection you chose above so that we can analyze the insightful comments and ideas and take the necessary steps for this topic. Thank you

Send Feedback

  • Mysql no compatible servers were found ошибка
  • Mysql installer accounts and roles ошибка
  • Myriwell 3d ручка ошибка
  • My mum is the actress где ошибка
  • My lands ошибка 403