*免责声明:如果有一个简单的解决方案,我提前道歉 - 我已经看过很多与我的类似的其他示例,但不知道如何解决这个问题。
我正在尝试计算示例数据库中使用相同提货地点的客户数量。
连接到数据库后,我有以下代码:
$Table="Customer";
$custPerLocationCount = sprintf("SELECT COUNT('userName') FROM %s as total WHERE 'pickUpLocationID'='1'", $Table);
$result = mysqli_query($db, $custPerLocationCount);
$body .= "<h1>Customers Per Location</h1><table align='center'>
<tr>
<th>Location Name</th>
<th>Number of Customers</th>
</tr>";
while ($recordArray = mysqli_fetch_object($result))
{
$locationName = "LOCATION1";
$custCount = print_r($result['total']);
$body .= "<tr>
<td>".$locationName."</td>
<td>".$custCount."</td>
</tr>";
};
$body .="</table></br></br></br>";
请忽略表格格式。当我更改代码时,我不断收到不同的错误,但尚未找到如何解决此问题。
最佳答案
在mysql中,您使用`使数据库将内容解释为列名,因此您必须更改查询以删除列中的引号,并且必须移动别名总计到SELECT语句末尾和FROM之前:
custPerLocationCount = sprintf("SELECT COUNT(`userName`) as total FROM %s WHERE `pickUpLocationID`='1'", $Table);
关于PHP MySQL 计数查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27284914/