yank yank - 7 months ago 54
SQL Question

why mysql_num_rows always returns 0 in php

I am using php script to make login page. I use mysql_num_rows() method,
it returns 1 if it matches first row only, it returns 0 when second or third row matches.

Here is My code:

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT id,username,password FROM user_data WHERE username = '$username' and password = '$password'";
$result = mysqli_query($sql);
$count = mysqli_num_rows($result);


Here I also tried mysqli method too, but result are same.

Please Help

Answer

Seeing your previous question How to insert array of array in phpmyadmin using php

You're using the MySQL_ API to connect with (or most likely, seeing the use of mysql_ functions, and you probably thought that you would slip in a few i's to those MySQLi_ functions along with MySQL_.

  • Well, you can't.

You need to use the same API from connecting to querying.

However, if you are using MySQLi_ to connect with (which is unknown), you didn't pass the db connection to your query and as the first parameter.

For this line $result = mysqli_query($sql);

Which would look something like:

$result = mysqli_query($connection, $sql);

Also make sure that your POST arrays do contain values.

Consult the manual on connecting with the MySQLi_ API:

Other links to consult to debug:

And as stated in comments:

Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.

Comments