准备好的陈述 - 行数

Kev*_*vin 11 php mysql prepared-statement

我正在学习预处理语句并尝试使用产生多行结果的查询.现在,我只想弄清楚如何确定行数,然后在html中显示该数字.

我准备好的陈述如下:

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();
   }
Run Code Online (Sandbox Code Playgroud)

我明白我应该先保存结果,然后使用num_rows,如下所示:

$stmt->store_result();
$stmt->num_rows;
Run Code Online (Sandbox Code Playgroud)

但是,当我把那些代码放在那里时,我正在运行并发布页面问题.我甚至无法进入如何显示行数的下一步

所以,问题是:在计算预准备语句中的行数方面我缺少什么,那么我将如何显示它 <?php echo '# rows: '.$WHATGOESHERE;?>

谢谢!!

Kev*_*Pei 16

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

/*.....other code...*/
$numberofrows = $stmt->num_rows;
/*.....other code...*/

echo '# rows: '.$numberofrows;
Run Code Online (Sandbox Code Playgroud)

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

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();
    $numberofrows = $stmt->num_rows;

    /* Close statement */
    $stmt -> close();
   }
echo '# rows: '.$numberofrows;
Run Code Online (Sandbox Code Playgroud)

  • 另外,我认为这是'$ stmt-> store_result();' 需要在num_rows行之前添加. (6认同)