Case Case - 1 month ago 15
MySQL Question

mysqli num rows gives error on server not localhost

I created a helper function and i use this a lot throughout my code get the following error.

but what i don't understand is I have zend server and my code runs fine on local host. why the grieve on a live server.


Warning: mysqli_ num_rows() expects parameter 1 to be mysqli_result, boolean on line 26


this is line 26

function row_count($result){
global $connection;
return mysqli_num_rows($result);
}



login code


function login_user($email, $password){

$active = 1;

$connection = dbconnect();
$stmt = $connection->prepare('SELECT user_pwd, user_id, username FROM users WHERE user_email = ? AND active= ?');
$stmt->bind_param('ss', $email, $active);
$stmt->execute();
$result = $stmt->fetch();

if (row_count($result) == 1) {

$row = fetch_array($result);

$db_password = $row['user_pwd'];

if (password_verify($password, $db_password)) {

$_SESSION['email'] = $email;
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];

return true;

} else {

return false;
}

return true;

} else {

return false;
}
}

Answer

Look at this statement here,

$result = $stmt->fetch();

From the documentation of mysqli_stmt::fetch,

                                    Return Values 
    Value    Description
    TRUE     Success. Data has been fetched
    FALSE    Error occurred
    NULL     No more rows/data exists or data truncation occurred

First, ->fetch() doesn't return any result set on success. And second, this method is used to fetch results from a prepared statement into the bound variables, which you're not doing.

Use ->store_result() followed by ->num_rows(), like this:

function login_user($email, $password){
    $active = 1;

    $connection = dbconnect();
    $stmt = $connection->prepare('SELECT user_pwd, user_id, username FROM users WHERE user_email = ? AND active= ?');
    $stmt->bind_param('ss', $email, $active);
    $stmt->execute();
    $stmt->store_result();     

    if ($stmt->num_rows == 1) {

        // your code        

    } else {
        return false;
    }
}
Comments