如何调试php/MySQL COUNT(id)返回1而不是总条目值 [英] How to debug php/MySQL COUNT(id) returning 1 instead of total entries value

查看:61
本文介绍了如何调试php/MySQL COUNT(id)返回1而不是总条目值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need the total number of entries in my database.

问题:为什么"print_r($ rows)"行返回"Array([COUNT(id)] => 79)",但随后"$ recordCount = Count($ row);则回显"
记录计数=.$ recordCount;"返回记录计数= 1".

Question: Why does the line "print_r($rows)" return "Array ( [COUNT(id)] => 79 )" but then the line "$recordCount = Count($row); echo "
record count = " . $recordCount;" returns "record count = 1".

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

I've tried a massive amount of different versions of this code, but I cant type them all here or it would take forever to read. Here is the current version of the code, which is giving me the unexpected results I mention above:

// 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年有人在网上阅读并发现很多错误的实现方法,

THANKS TO YOU HEROES I NOW HAVE IT CORRECT: Here incase someone else in 2018 is reading online and finding lots of incorrect implementations of it:

 $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 is an associative array with an entry for every column in the result set. Since there's only one column there, count($row) returns 1. Instead, you should just access the only column there:

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

这篇关于如何调试php/MySQL COUNT(id)返回1而不是总条目值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆