我想基于photo
计算product id
。我认为循环计数中有一些事情要做。所以我编码如下,但是我得到了
致命错误:在非对象上调用成员函数fetch_assoc()
<?
include_once($_SERVER['DOCUMENT_ROOT']."/cgi-bin/connect.php");
$stmt=$mysqli->prepare("select * from products_db order by prd_id");
$stmt->execute();
$result=$stmt->get_result();
$data=array();
while($row=$result->fetch_assoc()){
//count no. of img in loop
$stmt=$mysqli->prepare("select pic_id from photo_db where pic_sid=?");
$stmt->bind_param('s',$row['prd_sid']);
$result=$stmt->get_result();
$nPic=$result->num_rows;
$data[]=array($row['prd_code'],$row['prd_en'],$row['cat_id'],
number_format($row['prd_cost']),$row['prd_stts'],$nPic,$row['prd_rcm']);
}
echo json_encode(array('data' => $data));
?>
然后我去做:
$stmt=$mysqli->prepare("select *,count(pic.pic_id) as npic
from products_db prd
inner join
photo_db pic
on prd.prd_sid=pic.pic_sid
order by prd.prd_id");
它正在工作但由于与pic_sid
中的photo_db
无关联而未显示某些产品
我希望所有产品都显示照片计数,即使数据库中不存在这些照片也是如此。
答案 0 :(得分:0)
尝试此查询,希望它能工作。
select count(pi.pic_id),pr.* from photo_db pi where pi.pic_sid in (select pr.prd_sid from products_db pr ) group by pi.pic_id
答案 1 :(得分:0)
感谢@Sayed Mohd Ali
的建议。我想出了解决方案。
select *,
(select count(pic_id) as npic from photo_db where pic.pic_sid=prd.prd_sid) as npic
from products_db prd
left join photo_db pic on pic.pic_sid=prd.prd_sid
group by prd.prd_sid