LaideLawal
LaideLawal

Reputation: 77

php mysql fetch data from mulitiple table in json

Please help, I need to fetch data from two tables, and encode it in json my table are

  1. Customers_table

id | inv_id | customer_name | address | total_value

  1. Items_table

id | inv_id | description | details | qty | unit_price

my PHP code is as followws

<?php
require "config.php";

$sql = "SELECT customers_table.id,
                customers_table.inv_id,
                customers_table.customer_name,
                customers_table.address,
                customers_table.total_value,
                items_table.inv_id,
                items_table.description,
                items_table.details,
                items_table.inv_id,
                items_table.qty,
                items_table.ubit_price,
                items_table.amount,

                FROM customers_table INNER JOIN items_table ON
                customers_table.inv_id = items_table.inv_id;";
$result = mysqli_query($db, $sql);
$response = array();

while ($row = mysqli_fetch_array($result))
    {
    array_push($response);
    }

echo json_encode(array(
    "server_response" => $response
));
mysqli_close($db)
?>

but JSONLint response is

{
    "server_response": []
}

please, what am I doing wrong?

Upvotes: 1

Views: 269

Answers (1)

Touheed Khan
Touheed Khan

Reputation: 2151

array_push() accepts two parameters like this array_push($array, $element_to_be_pushed). array_push reference

You can rewrite same code by using $array[], this will push new elements to the next available index.

Try this code:

<?php
require "config.php";
$sql ="SELECT customers_table.id,
                customers_table.inv_id,
                customers_table.customer_name,
                customers_table.address,
                customers_table.total_value,
                items_table.inv_id,
                items_table.description,
                items_table.details,
                items_table.inv_id,
                items_table.qty,
                items_table.ubit_price,
                items_table.amount
                FROM customers_table INNER JOIN items_table ON
                customers_table.inv_id = items_table.inv_id;";
$result = mysqli_query($db, $sql);

$response = array();

while($row = mysqli_fetch_array($result))
{
    $response[] = $row;
}
echo json_encode(array("server_response"=> $response));
mysqli_close($db)
?>

Updated answer :

extra comma "items_table.amount," removed.

Upvotes: 3

Related Questions