简体   繁体   English

具有SUM()的PDO :: FETCH_ASSOC无法正常工作?

[英]PDO::FETCH_ASSOC with SUM() not working?

Why doesn't this work? 为什么不起作用?

$selectAllCount = $db->prepare("SELECT SUM(`count`) FROM `Test_Table`");
$selectAllCount->execute();

while($allCountRow = $selectAllCount->fetch(PDO::FETCH_ASSOC)) {
    echo $allCountRow['count'];
}

I have tried many other methods with mysql_libs and none of them seem to work, what's wrong here? 我用mysql_libs尝试了许多其他方法,但它们似乎都不起作用,这怎么了?

Make sure to give the column a name: 确保为列命名:

$selectAllCount = $db->prepare("SELECT SUM(`count`) as count FROM `Test_Table`");

Now you'll be able to fetch the result as you wanted. 现在,您将能够根据需要获取结果。

This seems to be the best way: 这似乎是最好的方法:

$selectAllCount = $db->prepare("SELECT SUM(`count`) FROM `Test_Table`");
$selectAllCount->execute();
$count = $selectAllCount->fetchColumn(0);

Documentation: http://php.net/manual/en/pdostatement.fetchcolumn.php 文档: http : //php.net/manual/en/pdostatement.fetchcolumn.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM