带有准备好的语句的mysqli_stmt_num_rows不返回行数

时间:2019-09-28 13:23:57

标签: php select mysqli prepared-statement

Prepared语句在应返回一行时将返回0行:

我的代码:

  $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));

我的数据
enter image description here

输出:
enter image description here


我在哪里错...?
$ myresult应该为1,因为在那里 IS 这样的行...

1 个答案:

答案 0 :(得分:2)

您已经正确注意到mysqli_stmt_store_result($stmt);之后需要mysqli_stmt_execute($stmt);
根据PHP文档:

  

如果使用mysqli_stmt_store_result(),则可能会立即调用mysqli_stmt_num_rows()。

但是,我需要指出的是,您不需要它,或者实际上您根本不需要使用mysqli_stmt_num_rows()。我认为我自己也不必使用此功能。

您想要实现的是检查DB中是否存在特定行。可以按照此处所述进行操作: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));

当然可以使用(bool) $stmt->get_result()->fetch_row()代替(bool) $stmt->get_result()->num_rows