php - 如何在while循环中运行sql查询
问题描述
我有两个数据库,需要在数组中获取它们并计算一行的数量,但是当我将第二个查询放入 while 循环时它根本不起作用,当我但它在循环之外时,我只计算了我的 1db 的最后一个养蜂场:
apiary_id , apiary_name
1 A
2 B
3 c
4 d
我的 2db:
hive_id, hive_number, apiary_id
1 01 1
2 02 2
3 02 1
4 04 2
5 05 4
我的PHP代码:
<?php
include 'db/db_connect.php';
//Query to select apiary id and apiary name
$query = "SELECT apiary_id, apiary_name, FROM apiaries";
$result = array();
$apiaryArray = array();
$response = array();
//Prepare the query
if($stmt = $con->prepare($query)){
$stmt->execute();
//Bind the fetched data to $apiaryId and $apiaryName
$stmt->bind_result($apiaryId,$apiaryName);
//Fetch 1 row at a time
while($stmt->fetch()){
//Populate the apiary array
$apiaryArray["apiary_id"] = $apiaryId;
$apiaryArray["apiary_name"] = $apiaryName;
$count = mysqli_num_rows(mysqli_query($con, "SELECT hive_id FROM hives WHERE hives.apiary_id".$apiaryId));
$apiaryArray["hive_count"] = $count;
$result[]=$apiaryArray;
}
$stmt->close();
$response["success"] = 1;
$response["data"] = $result;
}else{
//Some error while fetching data
$response["success"] = 0;
$response["message"] = mysqli_error($con);
}
//Display JSON response
echo json_encode($response);
?>
我需要这样的结果:
Apiary ID - Apiary Name - Count of Hives
1 A 2
2 B 2
3 c 0
4 d 1
如果有人帮助我,我会很高兴。
解决方案
你有错别字
hives.apiary_id =1".$apiaryId
应该
hives.apiary_id =".$apiaryId
所以整个陈述应该是,
$count = mysqli_num_rows(mysqli_query($con, "SELECT count(*) FROM hives WHERE hives.apiary_id =".$apiaryId));
推荐阅读
- javascript - Javascript 问题 - 未捕获的类型错误:当我单击删除图标时无法读取未定义的属性 'incart'
- debugging - 调试 Rocke-chip 凿子代码的最佳方法是什么?
- javascript - 将一些内容添加到
通过JS标记 - sql-server - SQL 表分区和文件组备份恢复
- android - 找不到 RecyclerView
- php - 如何在用电子表格(),php生成的.csv文件中显示带小数的整数?
- json - 如何在 vuetify 中导入 json 文件?
- javascript - NodeJS:如何在 Javascript / PNGJS 中创建 RGBA PNG 或 TGA
- lua - 罗技鼠标:一键 = 2 键按下
- azure-servicebus-topics - Azure service bus can u configure topic to only accept xml according to xsd?