Rafael
Rafael

Reputation: 157

Select query return 0 rows with prepare statement

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 = "[email protected]"; 
        $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.

Upvotes: 1

Views: 204

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269493

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.

Upvotes: 3

Related Questions