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

时间:2019-03-13 13:41:03

标签: php

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

如果有人帮助我,我会很高兴。

1 个答案:

答案 0 :(得分: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));