【问题标题】:Count rows from an SQL statement and store in PHP variable [duplicate]计算 SQL 语句中的行数并存储在 PHP 变量中 [重复]
【发布时间】:2021-11-21 19:47:58
【问题描述】:

我的 PHP 文件中有以下 SQL 代码。我想计算返回的行数并将其存储在一个变量中,以便我可以将其输出到页面上。

我尝试了一些我找到的解决方案,但都没有奏效。

$stmt = $con->prepare('SELECT id, owner_id, hs_name, hs_address FROM hotspots WHERE owner_id = ?');
$stmt->bind_param('i', $_SESSION['id']);

$stmt->execute();
$stmt->bind_result($hsid, $ownerid, $hsname, $hsaddress);

while($stmt->fetch()) {
    // print results in loop
}

任何帮助将不胜感激。

【问题讨论】:

  • 哈,真是巧合!不幸的是,我无法让它为我工作。

标签: php mysqli


【解决方案1】:

我通过添加解决了这个问题

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

执行后,整个事情现在看起来像

$stmt = $con->prepare('SELECT id, owner_id, hs_name, hs_address FROM hotspots WHERE owner_id = ?');
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->bind_result($hsid, $ownerid, $hsname, $hsaddress);

【讨论】:

    【解决方案2】:

    MySQLi 提供了一种很好的方法,您可以在语句执行后简单地在语句上使用num_rows 属性。这将立即返回语句返回的行数。

    $stmt->execute();
    $count = $stmt->num_rows;
    

    【讨论】:

    • 我实际上已经尝试过了——它出于某种原因返回 0。我的演示的实际回报应该是 2。它肯定会返回 2 个结果,因为我可以打印它们。
    • @JamesGrunshaw 您使用的是哪个 SQL 引擎? MySQL、SQLite、...?
    猜你喜欢
    • 2021-11-06
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多