首页 > 解决方案 > 如何在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

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

标签: php

解决方案


你有错别字

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));

推荐阅读