douren7179 2016-06-04 15:03
浏览 44
已采纳

选择查询使用prepare语句返回0行

I have problem in my sql prepare statement. I try to do select query to check if email is exist in the db, after that i check if the statement return any row, if its return that mean the email is already exist and i return "Email found", and if its not it should return "Email not found".

Now the problem is the email i try to check is exist in the db but i still get "Email not found".

Here is my php code:

try{
        $servername = "localhost";
        $dbusername = "xxx";
        $dbpassword = "xxx";
        $dbname = "xxx";

        // Create connection
        $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);

        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }


        $stmt = $conn->prepare(" SELECT `Email` FROM `Accounts` WHERE `Email`='?' ");
        // set parameters and execute            
    $emaila = "test001@gmail.com"; 
        $stmt->bind_param('s', $emaila);
        $stmt->execute();
    // if the email is not found
        if(mysqli_stmt_num_rows($stmt) == 0){
            $stmt->close();
            $conn->close();
            $data['success'] = false;
    $data['message']  = 'Email not found';
            echo json_encode($data);
        }
        else{
            $stmt->close();
            $conn->close();
            $data['success'] = false;
    $data['message']  = 'Email found';
            echo json_encode($data);
        }

    }
    catch(Exception $e){
        $data['success'] = false;
        $data['message'] = 'Error found';
        echo json_encode($data);
    }

I tried to play with the quotes but its just not worked, i spend 3 hours on that. Please help.

  • 写回答

1条回答 默认 最新

  • dqvzfp6468 2016-06-04 15:09
    关注

    You don't need the single quotes with a prepared statement. So:

    SELECT `Email` FROM `Accounts` WHERE `Email` = ?;
    

    Why not? The SQL interpreter knows the type of the parameter, when it is input. Hence, the single quotes are redundant (and actually harmful in this case). You can think of a string (or date) parameter as going into the query string along with a pair of single quotes to identify it as a string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?