【问题标题】:Get amount of rows in prepared statement获取准备好的语句中的行数
【发布时间】:2021-08-23 11:34:57
【问题描述】:

我正在使用通过字符串连接构建的准备好的语句查询:

  • $sqlitemsparse- “选择”子句
  • $sqlitemsparse . - “Where”子句
  • $sqlitemsparse2 - “限制”选择

这是按预期工作的。

现在,另外,我需要来自 $sqlitemsparse$sqlitemsparse . 查询的结果行数(没有“限制”选项)。

我已尝试将 mysqli_num_rows 函数与新的 mysqli_query 结合使用,但出现以下错误:

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given in...

代码:

$conn = new mysqli("localhost", "xxxx", "xxxx", "xxxx");

// Variable to bind
$classid = "4";

$sqlitemsparse = "SELECT * FROM itemSparse INNER JOIN item ON item.id = itemSparse.id";

$sqlitemsparse.= " WHERE item.ClassID = ?";

$sqlitemsparse2 = " LIMIT 0, 10";

$stmt = mysqli_stmt_init($conn);

if (!mysqli_stmt_prepare($stmt, $sqlitemsparse . $sqlitemsparse2)) {
    echo "SQL Failed";
} else {

    mysqli_stmt_bind_param($stmt, "s", $classid);
    mysqli_stmt_execute($stmt);

    $resultitemsparse = mysqli_stmt_get_result($stmt);

    while($rowitemsparse = mysqli_fetch_assoc($resultitemsparse)) {
        $rowsitemsparse[] = $rowitemsparse;
    }
}

$number_filter_row = mysqli_num_rows(mysqli_query($conn, $sqlitemsparse));

【问题讨论】:

  • 首先开启mysqli的报错How to get the error message in MySQLi?
  • 我启用了错误报告,输出是“警告”消息。我的想法是重复sqlitemsparse 查询,这样我就可以在没有$sqlitemsparse2 限制查询的情况下计算行数。

标签: php mysqli prepared-statement


【解决方案1】:

如果您想获取由同一预准备语句匹配但没有LIMIT 的行数,那么您需要执行另一个预准备语句,但这次使用SELECT COUNT(*) 而不是SELECT *

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli("localhost", "xxxx", "xxxx", "xxxx");

// Variable to bind
$classid = "4";

$sqlitemsparse = "SELECT * FROM itemSparse INNER JOIN item ON item.id = itemSparse.id";
$sqlitemsparse .= " WHERE item.ClassID = ?";

$sqlitemsparse2 = " LIMIT 0, 10";

$stmt = $conn->prepare($sqlitemsparse . $sqlitemsparse2);
$stmt->bind_param('s', $classid);
$stmt->execute();
$resultitemsparse = $stmt->get_result();
$rowsitemsparse = $resultitemsparse->fetch_all(MYSQLI_ASSOC);

$sqlitemsparse = "SELECT COUNT(*) FROM itemSparse INNER JOIN item ON item.id = itemSparse.id";
$sqlitemsparse .= " WHERE item.ClassID = ?";
$stmt = $conn->prepare($sqlitemsparse);
$stmt->bind_param('s', $classid);
$stmt->execute();
$resultitemsparse = $stmt->get_result();
$row_count = $resultitemsparse->fetch_row()[0]; // first column of first row

【讨论】:

  • 那么除了用SELECT COUNT(*) 修改$sqlitemsparse 查询之外没有别的可能吗?我最初的想法是两次使用完全相同的$sqlitemsparse
  • @Berstos 否。另一种方法是将数据库中的所有内容提取到 PHP 中并让 PHP 完成所有工作,但这会破坏拥有数据库的目的。 SQL 可以有效地执行计数,所以这真的不是问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多