一尘不染

如何调试php / MySQL COUNT(id)返回1而不是总条目值

sql

我需要数据库中的条目总数。

问题:为什么“ print_r($ rows)”行返回“ Array([COUNT(id)] => 79)”,但是随后“ $ recordCount =
Count($ row);”行却回显“
record count =”。$ recordCount;“ 返回“记录计数= 1”。

我已经尝试了此代码的大量不同版本,但无法在此处键入所有内容,否则将永远无法阅读。这是代码的当前版本,它给了我上面提到的意外结果:

// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}


$sql = "SELECT * FROM games ORDER BY id DESC LIMIT $startRow, $rowsPerPage";
$result = $conn->query($sql);

$sql = "SELECT COUNT(id) FROM games";
$results = $conn->query($sql);
$row = $results->fetch_assoc();
print_r($row);
$recordCount = Count($row);
echo "<br/> record count = " . $recordCount;



$totalPages = ceil($recordCount / $rowsPerPage);
$pagination = "<div class='pagination'>";

for ($i = 0; $i <= $totalPages; $i++) {
  $pagination .= "<a href='index.php?page=" . $i . "'>" . $i . "</a>";
  echo 'wtf!';
}

$pagination .= "</div>";
echo ' <br/> pagination = ' . $pagination;

谢谢你,我现在已经纠正了:如果万一2018年的其他人正在网上阅读并发现许多错误的实现方法,请执行以下操作:

 $sql = "SELECT COUNT(id) as countid FROM games";
$results = $conn->query($sql);
$row = $results->fetch_assoc();

$recordCount = $row["countid"]; // the countid gives me the total i expected :DDDD
echo "<br/> record count = " . $recordCount;

阅读 131

收藏
2021-05-30

共1个答案

一尘不染

row是一个关联数组,结果集中的每个列都有一个条目。由于那里只有一列,因此count($row)返回1。相反,您应该只访问那里的唯一列:

$row = $results->fetch_assoc();
$recordCount = $row["COUNT(id)"];
2021-05-30