我正在尝试通知用户登录位置,并查看他们登录首页时仍然有多少个待处理的请求。但是,我得到这个错误,它说count参数必须是数组或对象
count():参数必须是实现Countable的数组或对象
我做错了什么,应该如何解决?谢谢。
<?php
$sql = "SELECT status,request
FROM orders
WHERE status = 'Pending'
OR request = 'Pending'";
$result = $conn->query($sql);
if(!$result) die($conn->error);
$rows = $result->num_rows;
if (COUNT($rows['status']) OR COUNT($rows['request']) > 0) {
echo "You have ".(COUNT($rows['status']) + COUNT($rows['request']))."pending notificatins.";
}else{
echo "You have 0 pending notifications.";
}
?>
答案 0 :(得分:0)
获取所有行只是为了对它们进行计数是没有意义的。您需要其他查询:
SELECT COUNT(request)
FROM orders
WHERE status = 'Pending'
OR request = 'Pending'
答案 1 :(得分:-1)
我认为您也许可以实现这样的目标:在sql中分配每个计数,然后重要的是,获取记录集以开始处理。
<?php
$sql = 'select
( select count(*) from `orders` where `status`='pending' ) as `status-count`,
( select count(*) from `orders` where `request`='pending' ) as `request-count`';
$result = $conn->query( $sql );
$rows = $result->num_rows;
if( $result && $rows > 0 ){
$rs = $result->fetch_all( MYSQLI_ASSOC );
$status=$rs[0]['status-count'];
$request=$rs[0]['request-count'];
if( $status > 0 or $request > 0 ){
printf('You have %s pending notifications: [ Status=%d, Request=%d ]', ( $status + $request ), $status, $request );
}else{
echo 'You have 0 pending notifications.';
}
}
?>
对于问题中的PHP逻辑,确实确实存在一个简化的查询,例如下面的@marcin orlowski所示,它会给出正确的计数并允许该逻辑起作用,因此您无法根据自己的意愿确定,有多少status
或requests