Php 如何在while循环中运行sql查询
我有两个db,需要在数组中获取它们,还需要计算一行的数量,但当我在while循环中放入第二个查询时,它根本不起作用,当我在while循环外放入第二个查询时,它只给了我最后一个数组的数量 我的1db: 我的2db:Php 如何在while循环中运行sql查询,php,Php,我有两个db,需要在数组中获取它们,还需要计算一行的数量,但当我在while循环中放入第二个查询时,它根本不起作用,当我在while循环外放入第二个查询时,它只给了我最后一个数组的数量 我的1db: 我的2db: hive_id, hive_number, apiary_id 1 01 1 2 02 2 3 02 1 4
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);
?>
如果有人帮助我,我会很高兴的 你的拼写错误
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));
我发现您的代码存在多个问题。我的建议是尝试将您的逻辑整合到一个查询中,这看起来是可能的,至少快速浏览一下。结果将出现在json数组中,对吗?-Nancy Moore YesTim Biegeleisen是否可以帮助我精简?保持紧密,我正在处理它谢谢我解决了同样的问题。当我删除第二个查询php时,它是工作的,但当我在while循环中写入时,它不工作
hives.apiary_id =".$apiaryId
$count = mysqli_num_rows(mysqli_query($con, "SELECT count(*) FROM hives WHERE hives.apiary_id =".$apiaryId));