简体   繁体   中英

mysqli_stmt_num_rows with prepared statement doesn't return number of rows

Prepared statement returns 0 rows when it should return a row:

My code:

  $conn = mysqli_connect("localhost", "root", "", "test1");
  $myUser = "qqq";
  $stmt = mysqli_stmt_init($conn);
  $sql = 'SELECT `userMail` FROM `users` WHERE `userName`=? LIMIT 1';
  mysqli_stmt_prepare($stmt, $sql);
  mysqli_stmt_bind_param($stmt, "s", $myUser);
  mysqli_stmt_execute($stmt);
  $myresult = mysqli_stmt_num_rows($stmt);
  die(nl2br("myUser = ".$myUser."\nmyresult = ".$myresult));

My data:
在此处输入图像描述

The output:
在此处输入图像描述


Where am I wrong...?
$myresult should be 1, for there IS such a row...

As you have already correctly noticed you need mysqli_stmt_store_result($stmt); after mysqli_stmt_execute($stmt); .
As per PHP docs:

If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be called immediately.

However, I need to point out that you don't need it, or in fact you do not need to use mysqli_stmt_num_rows() at all. I don't think I ever had to use this function myself neither.

What you are trying to achieve is to check if a particular row exists in DB. This can be done as mentioned here: https://phpdelusions.net/mysqli/check_value

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli("localhost", "root", "", "test1");

$myUser = "qqq";

$sql = 'SELECT 1 FROM `users` WHERE `userName`=? LIMIT 1';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $myUser);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row();

die(nl2br("myUser = ".$myUser."\nmyresult = ".$exists));

Of course instead of (bool) $stmt->get_result()->fetch_row() you could use (bool) $stmt->get_result()->num_rows .

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