繁体   English   中英

如何在 while 循环中运行 sql 查询

[英]How to run an sql query inside a while loop

我有两个数据库,需要在数组中获取它们,还需要计算一行的数量,但是当我将第二个查询放入 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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM