Sini
Sini

Reputation: 406

Save query results in one array

I am absolute beginner with PHP. I am currently working on an Android App which has a webservice with PHP. I need to get the results of 2 executed SQL-Querys and convert it to json. My Problem is I do not get any result back to client, also I do not get any error. I think it is because I divided results into two arrays. How can I save the results of the 2 queries as one array, so as one json response?

Code EDITED:

<?php
    $host = "localhost"; // host of MySQL server
    $user = "root"; // MySQL user
    $pwd = ""; // MySQL user's password
    $db = "food"; // database name

    // Create connection
    $con = mysqli_connect($host, $user, $pwd, $db);

    // Check connection
    if(mysqli_connect_errno($con)) {
        die("Failed to connect to MySQL: " . mysqli_connect_error());
    } 
    //$uname = $_POST['uname'];

    // query the application data
    $sql = "SELECT * FROM uploads WHERE status = '0' ORDER By  precious_time DESC";
    $sql2 = "SELECT * FROM uploads_avatar WHERE uname = 'sinii'";

    $result = mysqli_query($con, $sql);
    $result2 = mysqli_query($con, $sql2);

    // an array to save the application data
    $rows = array();
    $rows2 = array();

    // iterate to query result and add every rows into array
    while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        $rows[] = $row; 

    }

    // iterate to query result and add every rows into array
    while($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
       $rows2[] = $row2; 

    }

    $result_merge = array_merge($rows, $rows2);

    // close the database connection
    mysqli_close($con);


    // echo the application data in json format
    echo json_encode($result_merge);
    ?>

However I run the application without the second query with the second array etc., then it works, but I need the data of the second query too.

Thanks for any help!

Upvotes: 0

Views: 207

Answers (2)

kingtut007
kingtut007

Reputation: 89

Why dont you just use a MySQL query to merge the two tables when querying??

select * from uploads,uploads_avatar where uploads.status = '0' and uploads_avatar.uname = 'sinii';

Upvotes: 0

rahulinaction
rahulinaction

Reputation: 354

For getting value in one array use array_merge to merge both the arrays or you could do it i n this format

$jsonResult = array();

while($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
  $jsonResult["uploads"][] = $row; 
}


while($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
  $jsonResult["upload_avatar"][] = $row2; 
}

echo json_encode($jsonResult);

Using array merge

 $jsonResult = array_merge($rows, $rows2);
   echo json_encode($jsonResult);

As for json response you should first check the response by seeing the response in a web browser first.

Upvotes: 1

Related Questions