user3001162 user3001162 - 2 months ago 8
MySQL Question

Why is mysqli_query failing - returning object when it should return resource

I have tried everything to find out why mysqli_query is failing. Can anyone shed light as to what I'm doing wrong. would be possible that I am not connecting to the dababase anymore??!! Thank you in advance!

function email_exists($email){
$email = sanitize($email);
$db = new mysqli('localhost','root','','secured_login');
if($db->connect_errno){
$connect_error = 'Sorry, we are experiencing connection problems.';
die ($connect_error);
}
return (mysql_result(mysqli_query($db, "SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email'"), 0) == 1) ? true : false;
}


error

Warning: mysql_result() expects parameter 1 to be resource, object given in....


Alternative solution using mysqli_fetch_row(); <----- Isthe below alternative valid?

function email_exists($email){
$email = sanitize($email);
$db = new mysqli('localhost','root','','secured_login');
if($db->connect_errno){
$connect_error = 'Sorry, we are experiencing connection problems.';
die ($connect_error);
}
$query = "SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email'";
if ($result = mysqli_query($db, $query)){
while ($result= mysqli_fetch_row($result)){
return ($result);
}
}
}


Any feedback is appreciated!

Answer

At it's simplest form, you should be looking at something similar to the following,

function email_exists($email){
    $email = sanitize($email);
    $db = new mysqli('localhost','root','','secured_login');
    if($db->connect_errno){
        $connect_error = 'Sorry, we are experiencing connection problems.'; 
        die ($connect_error);
    }
    $query = $db->query("SELECT `user_id` FROM `users` WHERE `email` = '$email'");
    return ($query->num_rows > 1) ? true : false;
}

Remember to sanitize your inputs, or even better, use prepared statements.

Comments