mysqli num_rows returning 0

2019-09-20 17:02发布

问题:

Can not figure out why this is not working. Have gone through other questions here, but it seems my code is fine.

$queryLink = $mysqli->prepare("SELECT vendor_name FROM vendors WHERE vendor_id='1'");
$queryLink->execute();
$queryLink->store_result;
$queryLink->bind_result($vendor_name);
$queryLink->fetch();
$numRows = $queryLink->num_rows;
$queryLink->close();

echo $vendor_name.'<br>'.$numRows;

The script returns this:

VendorNameHere
0

It is returning 1 record, but $numRows always stays 0. I have tried moving the numRows line to different places in the script, but it always returns 0. What am I doing wrong?

回答1:

This line:

$queryLink->store_result;

Should be a method call:

$queryLink->store_result();


回答2:

But you don't need number of rows here. Apparently there will be only one vendor with such id. Why bloat your code with useless function calls?

$id   = 1;
$stmt = $mysqli->prepare("SELECT vendor_name FROM vendors WHERE vendor_id=?");
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($vendor_name);
$stmt->fetch();

if ($vendor_name) {
    echo $vendor_name;
} else {
    echo "None found";
}

is all the code you need.



标签: php mysqli