Reputation: 21
i have two db and need to fetch them in array and also count number of one row but when i put second query inside while loop it dose not work at all and when i but it outside loop then gave me just count of last apiary my 1db:
apiary_id , apiary_name
1 A
2 B
3 c
4 d
my 2db:
hive_id, hive_number, apiary_id
1 01 1
2 02 2
3 02 1
4 04 2
5 05 4
my php code:
<?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);
?>
i need result like this:
Apiary ID - Apiary Name - Count of Hives
1 A 2
2 B 2
3 c 0
4 d 1
i will be happy if somebody help me.
Upvotes: 2
Views: 74
Reputation: 2866
You have a typo,
hives.apiary_id =1".$apiaryId
should be
hives.apiary_id =".$apiaryId
So the whole statement should be,
$count = mysqli_num_rows(mysqli_query($con, "SELECT count(*) FROM hives WHERE hives.apiary_id =".$apiaryId));
Upvotes: 1