简化:mysqli num_rows 不工作

2021-12-25 00:00:00 php mysql mysqli

如何使用mysqli输出返回的行数?我下面的代码通过 while 循环显示 0 (while $s->fetch() echo $uid;) 显示 2 个结果;

$m = new mysqli(MYSQL_SERVER, MYSQL_USER, MYSQL_PASS, MYSQL_DB);$s=$m->prepare("SELECT uid FROM user WHERE token=? AND secret=?");$s->bind_param('ss',$rt, $rs);$rt='c';$rs='d';$s->execute();$s->bind_result($uid);$s->fetch();print_r($s->num_rows);//结果为 0

解决方案

你必须在 mysqli_stmt::execute() 之后调用 mysqli_stmt::store_result()在获取之前为了知道 mysqli_stmt::num_rows:

$s->execute();$s->store_result();print_r($s->num_rows);

num_rows上的 PHP 文档

store_result() 上的 PHP 文档

How do I output the number of returned rows using mysqli? My code below shows 0 though a while loop (while $s->fetch() echo $uid;) shows 2 results;

$m = new mysqli(MYSQL_SERVER, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
$s=$m->prepare("SELECT uid FROM user WHERE token=? AND secret=?");
$s->bind_param('ss',$rt, $rs);
$rt='c';
$rs='d';
$s->execute();
$s->bind_result($uid);
$s->fetch();
print_r($s->num_rows); // RESULTS IN 0

解决方案

You'll have to call mysqli_stmt::store_result() after mysqli_stmt::execute() and before fetch in order to know mysqli_stmt::num_rows:

$s->execute();
$s->store_result();
print_r($s->num_rows);

PHP Document on num_rows

PHP Document on store_result()

相关文章