Search code examples
phpmysqlsqlmysqlimysql-num-rows

mysqli_num_rows = 0 when it should be 1


I've been trying to resolve this problem on my own and for the life of me can't fix it..

//If they are, retreive them from the Person table    
var_dump($_POST['username']);
var_dump($_POST['password']);
$select = $this-> doQuery("SELECT * FROM Person WHERE username = '{$_POST['username']}' AND password = '".md5($_POST['password'])."'");
var_dump($select);  

try {    
    if (mysqli_num_rows($select) > 0){
        var_dump(mysqli_num_rows($select));
        //fetching username and password from database
        $fetch_array = mysqli_fetch_assoc($select);
        var_dump($fetch_array);     
        //Building a session for the user
        $_SESSION['username'] = $fetch_array['username'];

        //var_dump($_SESSION['username']);

        //Redirecting the user to the index page        
        header('Location:index.php');
        return true;
    }

The two var_dumps on the username and password on the 4th and 5th lines returned this:

string(8) "johnny03" 
string(9) "password3" 
object(mysqli_result)#3 (5) { ["current_field"]=> int(0) ["field_count"]=> int(8) ["lengths"]=> NULL ["num_rows"]=> int(0) ["type"]=> int(0) } 

The values that I entered for both the password and username are both valid (they are in the database under the correct columns, trust me). I have a feeling that something is wrong with my select query because the var dump on mysqli_num_rows($select) doesn't return anything.That being said, I've tried just about every change to the query that I could think of to make it work and still nothing :[ Can anyone help?


Solution

  • First : Try removing the braces from the query :

    $select = $this-> doQuery("SELECT * FROM Person WHERE username = '{$_POST['username']}' AND password = '" . md5($_POST['password']) . "'");
    

    Edit : Braces are okay, see comment by drew010.

    If that isn't the problem, as noted by drew010, check your resulting hash (output it using a simple echo and compare it to your database.

    If those do seem to match, but there is a piece missing, then adjust the capacity of your password field in your database.

    Your password field most likely has a size e.g. varchar(20) which is too small for the entire hash to fit in. Adjust the size in your database and store the correct hash result.

    Also, at least see into some salting, md5 has been broken since a while now so you should replace it by a hash of the sha-family.

    You can verify the hash in the database as well by using an online md5 hashing and get the length by measuring it using strlen