Search code examples
phpmysqlimysql-num-rows

Can not figure out why mysqli_num_rows is not working on my query


function userexists($username){
    $query=$mysqli->query("SELECT username FROM accounts WHERE username='$username' AND exists=1");
    return mysqli_num_rows($query);
}

This function should be returning 1 or 0 but I can not figure out why the query is not being interpreted. What's wrong?

Edit: the error being returned by php is that $query is a boolean being fed into mysqli_num_rows, not an object.


Solution

  • In your query:

    SELECT username FROM accounts WHERE username='$username' AND exists=1"
    

    exists is a MySQL keyword. If you've used it as a column name then you'll get a syntax error. You could enclose the column name in back-ticks like this:

    SELECT username FROM accounts WHERE username='$username' AND `exists`=1"
    

    It's probably safer to change the column name and your query.

    Be careful of possible SQL Injection attacks. At the very least you should escape any user-supplied data with mysqli_real_escape_string($username)