如何调试php / MySQL COUNT(id)返回1而不是总条目值
技术问答
303 人阅读
|
0 人回复
|
2023-09-12
|
我需要数据库中的项目总数。/ X/ [+ S& b! x( Z, W
问题:为什么 print_r($ rows)行回 Array([COUNT(id)] => 79)$ recordCount =
5 |4 g/ T( T+ G; \ ACount($ row);行却回显
O* L6 a6 W+ |" k) M, Srecord count =”。$ recordCount; 返回记录计数= 1”。
% F" t+ U7 }0 t/ j5 Q' a; a* X) Z我尝试了很多不同版本的代码,但我不能在这里输入所有内容,否则我永远不会阅读。这是代码的当前版本,它给了我上面提到的意想不到的结果:6 w. v& ~2 b, o Y
// create connection$conn = new mysqli($servername,$username,$password,$dbname);// check connectionif ($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 "$ s) w6 j. f# I! q4 Q$ r/ p8 J
record count = " . $recordCount;$totalPages = ceil($recordCount / $rowsPerPage);$pagination = "";for ($i = 0; $i ";echo ' * H* g2 h. @9 s# F
pagination = ' . $pagination;谢谢你,我现在已经纠正了:如果其他人在2018年在网上阅读并发现许多错误的实现方法,请执行以下操作:
" r' J- w) Q) @2 _9 ] $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 DDDecho "% |8 s7 _9 n2 N7 Z
record count = " . $recordCount; # A0 I7 a% {1 x& {! U/ @% c& `, @1 T8 x
解决方案: - h4 {. ?1 h& D
row它是一个相关的数组,每个列的结果都有一个项目。因为那里只有一列,所以count($row)返回1。相反,您应该只访问那里的唯一列:
8 ]8 z3 F3 i0 L/ v8 S% Y$row = $results->fetch_assoc();$recordCount = $row["COUNT(id)"]; |
|
|
|
|
|