准备好的语句 - 行数

2021-12-25 00:00:00 php mysqli prepared-statement

我只是想弄清楚如何确定行数,然后在 HTML 中显示该数字.

I'm just trying to figure out how to determine the number of rows and then make that number display in the HTML.

我准备好的语句如下所示:

My prepared statement looks like this:

if($stmt = $mysqli -> prepare("SELECT field1, field2, field3 FROM table WHERE id= ?ORDER BY id ASC")) 
    {
    /* Bind parameters, s - string, b - blob, i - int, etc */
    $stmt -> bind_param("i", $id);
    $stmt -> execute();
    
    /* Bind results */
    $stmt -> bind_result($testfield1, $testfield2, $testfield3);
    
    /* Fetch the value */
    $stmt -> fetch();

    /* Close statement */
    $stmt -> close();
   }

我知道我应该先保存结果,然后使用 num_rows,就像这样:

I understand that I'm supposed to first save the results, then use num_rows, like this:

$stmt->store_result();
$stmt->num_rows;

但是,我正在运行,当我将代码放入其中时,页面会出现问题.我什至无法进入如何显示行数的下一步

However, I'm running, and issue with the page bugging out when I put that code in there. I haven't even been able to get to the next step of how to display the number of rows

在计算准备好的语句中的行数方面我缺少什么,那么我将如何使用 <?php echo '# rows: '.$WHATGOESHERE;?>

What am I missing in terms of calculating the number of rows inside the prepared statement, then how would I display it with a <?php echo '# rows: '.$WHATGOESHERE;?>

推荐答案

num_rows 返回数字,您必须将其存储在变量中.

num_rows returns the number, you have to store it in a variable.

/*.....other code...*/
$numberofrows = $stmt->num_rows;
/*.....other code...*/
    
echo '# rows: '.$numberofrows;

所以完整的代码应该是这样的:

So full code should be something like this:

$stmt = $mysqli -> prepare("SELECT field1, field2, field3 FROM table WHERE id= ? ORDER BY id ASC");
/* Bind parameters, s - string, b - blob, i - int, etc */
$stmt -> bind_param("i", $id);
$stmt -> execute();
$stmt -> store_result();

/* Bind results */
$stmt -> bind_result($testfield1, $testfield2, $testfield3);

/* Fetch the value */
$stmt -> fetch();
$numberofrows = $stmt->num_rows;

/* Close statement */
$stmt -> close();

echo '# rows: '.$numberofrows;

相关文章