为什么mysqli_query失败 - 当它返回资源时返回对象

时间:2014-01-27 11:53:15

标签: php mysql

我已经尝试了一切来找出mysqli_query失败的原因。任何人都能明白我做错了什么。有可能我不再连接到dababase了?? !!先感谢您!

  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;
}

错误

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

使用mysqli_fetch_row()的替代解决方案; < -----以下替代有效吗?

  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);
        }           
    }
}

感谢任何反馈!

2 个答案:

答案 0 :(得分:2)

以最简单的形式,您应该看到类似于以下内容的内容,

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;
}

请记住清理您的输入,或者甚至更好地使用prepared statements

答案 1 :(得分:0)

您将mysqlmysqli混为一谈,为什么?

我认为这是一个错字 - 但将mysql_result更改为mysqli_result