简体   繁体   中英

Prepared statement returns no results

I have been chasing my tale with this for a long time. I have not been able to find an issue with this code:

 $query = "SELECT * FROM CUSTOMER WHERE username = ?";
 $stmt = $db->prepare($query);
 $stmt->bind_param("s", $username);
 $stmt->execute();
 echo $stmt->num_rows." ".$username;`

The CUSTOMER table in my database has three columns: username, pwd, and email. But nonetheless, no results are returned when I assign the $username variable to a value I know exists in the database. I know it exists because this query

$results = $db->query("SELECT * FROM CUSTOMER WHERE username ='$username'");
echo $results->num_rows;

Displays one row, which is what is expected. Can anybody please tell me why my prepared statement will not produce the correct results? I have tried several variations of quoting, not quoting, hardcoding the variable's value, but nothing works. I am on a university server so I have no control over PHP's or MySQL's settings, but I'm not sure that has anything to do with it. It seems like a coding issue, but I can't see anything wrong with the code.

num_rows will be populated only when you execute $stmt->store_result(); .

However, 99.99% of the time you do not need to check num_rows . You can simply get the result with get_result() and use it.

$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
foreach($result as $row) {
    // ...
}

If you really want to get the num_rows, you can still access this property on the mysqli_result class.

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

You've executed the query successfully, but not done anything with the result .
After $stmt->execute(); , you're looking for $stmt->bind_result($result); .

With this, you'll have access to the user's information in the $result variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM