yathavan
yathavan

Reputation: 183

Multiple mysqli select with json

<?php
include"../database_conn.php";
$con=mysqli_connect("localhost","admin","123456","ayurveadic");

$query_pag_data = "SELECT id from diseases";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());

while ($row = mysql_fetch_array($result_pag_data)) {
    $diseases_id = $row['id'];

    $result = mysqli_query($con,"SELECT $diseases_id FROM treatment WHERE gender_id = '10' AND diseases_id = '$diseases_id'");
    $row_gid = mysqli_fetch_array($result);
    if ($row_gid == TRUE){

        $sl_dise = mysqli_query($con,"SELECT Diseases_type, id FROM diseases WHERE id = '$diseases_id'");

        $rowss = array();
        while($r = mysqli_fetch_assoc($sl_dise)) {
            $rowss[] = $r;
        }
        print json_encode($rowss);
    }
}

Output is:

[{"Diseases_type":"fever","id":"114"}][{"Diseases_type":"rhrh","id":"123"}]

How can i get this output:

[{"Diseases_type":"fever","id":"114"},{"Diseases_type":"rhrh","id":"123"}]

Upvotes: 0

Views: 723

Answers (3)

Ranjith
Ranjith

Reputation: 2819

Put your

print json_encode($rowss);

after end of thiswhile ($row = mysql_fetch_array($result_pag_data)) {

Also remove this $rowss = array(); array initialization

Upvotes: 0

Anish
Anish

Reputation: 5008

Here is you optimised code

<?php
include"../database_conn.php";
$con=mysqli_connect("localhost","admin","123456","ayurveadic");

 $query_pag_data = "select diseases.Diseases_type,diseases.id from diseases inner join treatment on treatment.diseases_id = diseases.id where treatment.gender_id = '10' ";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());

$rowss = array();
while ($row = mysqli_fetch_assoc($result_pag_data)) {
    $rowss[] = $row;
}
print json_encode($rowss);
?>

Upvotes: 1

Barmar
Barmar

Reputation: 780974

You need to initialize the JSON array before the outer loop, and print it at the very end, not each time through.

<?php
include"../database_conn.php";
$con=mysqli_connect("localhost","admin","123456","ayurveadic");

$query_pag_data = "SELECT id from diseases";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());

$rowss = array();
while ($row = mysql_fetch_array($result_pag_data)) {
    $diseases_id = $row['id'];

    $result = mysqli_query($con,"SELECT $diseases_id FROM treatment WHERE gender_id = '10' AND diseases_id = '$diseases_id'");
    $row_gid = mysqli_fetch_array($result);
    if ($row_gid == TRUE){

        $sl_dise = mysqli_query($con,"SELECT Diseases_type, id FROM diseases WHERE id = '$diseases_id'");

        while($r = mysqli_fetch_assoc($sl_dise)) {
            $rowss[] = $r;
        }
    }
}
print json_encode($rowss);

Upvotes: 2

Related Questions