gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:26:08 25 4
gpt4 key购买 nike

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

问题:为什么“print_r($rows)”行返回“Array ( [COUNT(id)] => 79 )”,但随后“$recordCount = Count($row); echo”行返回“
记录计数 = ". $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;

最佳答案

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

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

关于php - 如何调试 php/MySQL COUNT(id) 返回 1 而不是总条目值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51115033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com