0

I need to print multiple database queries using json_encode(). I have this code below that outputs database records using json_encode. This works fine.

<?php

error_reporting(0);
include('db.php');

$result = $db->prepare('SELECT username,firstname,lastname FROM user');
$result->execute(array());

$data = array();

while ($row = $result->fetch()) {
    $data[] = $row;
}

echo json_encode($data);

?>

I need to add another database query so that I can print them together using the same json_encode. Here is the database query that I want to add so that I can print them together using json_encode:

<?php

include('db.php');

$result = $db->prepare('SELECT price AS price1,goods AS product FROM provision_table');
$result->execute(array());

$data_pro = array();

while ($row = $result->fetch()) {
    $data_pro[] = $row;
}

echo json_encode($data_pro);
?>

How can I accomplish this?

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
nackolysis
  • 217
  • 4
  • 13

1 Answers1

0

I think this might hit what you're looking for.

<?php

error_reporting(0);
include('db.php');

$result = $db->prepare('select username,firstname,lastname from user');
$result->execute(array());

$data = array();

while ($row = $result->fetch()) {
    $data[] = $row;
}

$result = $db->prepare('select price as price1,goods as product from provision_table');
$result->execute(array());

$data_pro = array();

while ($row = $result->fetch()) {
    $data_pro[] = $row;
}

// Combine both arrays in a new variable
$all_data['user'] = $data;
$all_data['pro'] = $data_pro;

echo json_encode($all_data);
Nick
  • 16,066
  • 3
  • 16
  • 32
  • Hello dear, its not printing or outputting any value. everything value was just empty. I cannot figure out where you initialized $all_data variables. – nackolysis Aug 22 '16 at 19:07