1

So, I have a prepared statement that I have successfully prepared, bound, and executed:

SELECT * FROM users WHERE email = ? AND pass = SHA1(?)

It looks like one row is returned, as expected. However, why is the $result variable empty when I call @$stmt->get_result()? Thanks in advance.

$num_rows = mysqli_num_rows($stmt->get_result());

if ($num_rows == 1) {

    // Fetch the result set
    $result = $stmt->get_result();

    //if result empty echo false
    if(empty($result)) {
        echo "result is empty";
    }   
}
1
  • 2
    Silly question, but you call get_result() at the start of your code, and then call it again inside the if statement - are you sure that it'll return what you're expecting the second time it's called? Commented Mar 5, 2016 at 22:49

1 Answer 1

3

Just to put the two comments together and elaborate a litte....

<?php
$result = $stmt->get_result();
$num_rows = mysqli_num_rows($result);

if ($num_rows == 1) {
    // already fetched the mysqli_result
    // now lets fetch the one record from that result set
    $row = $result->fetch_assoc();
    // ....do something with row
}
else {
    // either 0   ...or more than 1 row
    foo();
}

But you can even get rid of the call to mysqli_num_rows() (so it also works in case of unbuffered queries)

$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ( !$row ) {
    // no such record
    foo();
}
else {
    // ....do something with row

    // might want to check whether there are more matching records
    // given the context there shouldn't, but ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.