准备好的陈述 - 行数

时间:2013-05-24 00:26:49

标签: 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();
   }

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

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

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

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

显示它?

谢谢!

4 个答案:

答案 0 :(得分:14)

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

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

echo '# rows: '.$numberofrows;

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

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;

答案 1 :(得分:1)

如果您只对行数感兴趣,而不对实际的数据行感兴趣,那么这里是一个完整的查询块,其中装有错误检查点和SELECT子句中建议的COUNT(*)调用。

if (!$conn = new mysqli("host", "user", "pass", "db")) {
    echo "Database Connection Error: " , $conn->connect_error;  // don't show this to the public
} else {
    if (!$stmt = $conn->prepare("SELECT COUNT(*) FROM `table` WHERE id= ?")) {
        echo "Prepare Syntax Error: " , $conn->error;  // don't show this to the public
    } else {
        if (!$stmt->bind_param("s", $id)              // if trouble while binding to ? placeholder
            || !$stmt->execute()                      // or if trouble while executing
            || !$stmt->bind_result($num_rows)         // or if trouble while binding to $num_rows
            || !$stmt->fetch()) {                     // or if trouble while fetching the one row.
            echo "Statement Error: " , $stmt->error;  // don't show this to the public
        }else{
            echo $num_rows;
        }
        $stmt->close();                               // no longer need statement
    }
    $conn->close();                                   // no longer need connection
}

或者,如果您想在迭代/处理行之前知道行数,一种方法是将整个结果集(多维数组)集中到一个变量中,然后在调用count() / sizeof()之前反复进行。

if (!$conn = new mysqli("host", "user", "pass", "db")) {
    echo "Database Connection Error: " , $conn->connect_error;
} else {
    if (!$stmt = $conn->prepare("SELECT field1, field2, field3 FROM table WHERE id= ? ORDER BY id ASC")) {
        echo "Prepare Syntax Error: " , $conn->error;
    } else {
        if (!$stmt->bind_param("s", $id)
            || !$stmt->execute()
            || !$result = $stmt->get_result()) {
            echo "Statement Error: " , $stmt->error;
        }else{
            $resultset = $result->fetch_all(MYSQLI_ASSOC);
            echo "<div>Num: " , sizeof($resultset) , "</div>";
            foreach ($resultset as $row) {
                echo "<div>Row: {$row['field1']} & {$row['field2']} & {$row['field3']}</div>";  // do what you like
            }
        }
        $stmt->close();
    }
    $conn->close();
}

*我已经在本地主机上测试了以上两个片段是否成功。

答案 2 :(得分:1)

此功能自 2020年2月开始:

$number_of_records = $stmt->rowCount();
echo $number_of_records;

摘自php.net手册:

PDOStatement :: rowCount()返回受a影响的行数 DELETE,INSERT或UPDATE语句。

这是他们网站上的example

<?php
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();

/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
?>

上面的示例将输出:

Return number of rows that were deleted:
Deleted 9 rows.

答案 3 :(得分:-2)

在这里查看示例#2: PHP.net

  

使用PDO :: query()发出SELECT COUNT(*)语句,其语句与预期的SELECT语句相同,然后使用PDOStatement :: fetchColumn()来检索将返回的行数。然后,您的应用程序可以执行正确的操作