Delphine le Bussy
Delphine le Bussy

Reputation: 43

Insert results of multiple tables into one json_encode()

Excuse my language mistakes, I speak French.

I did some research on this site and elsewhere, but what I have found didn't solve my problem.

I am doing a site where people can post their stories. I'm working on a page where the author should be able to see his stories and chapters of each of them.

I do a query on two tables to get the titles of stories and chapters. I have a table "stories" in which there is the title and summary of each story (and other stuff like id and date of publication). And another table called "chapters", in which there is the title of each chapter and the id of the story to which they belong.

I would like to retrieve these items later in my html, to have something like this:


Story title 1

Chapter 1

Chapter 2


So I do a json_encode () but JSONLint said that the json I get is invalid. PHP is new to me, I began to learn so I'm probably not writing my code correctly.

Here is my code:

<?php
session_start();
require_once('connexion_db.php');

if($db=connect()){
    $userID = $_SESSION['id'];

    $arr = array();

    $reqRecits = $db->query('SELECT titre, id FROM recits WHERE user_id = '.$userID.'');
    $resRecits = $reqRecits->fetchAll(PDO::FETCH_ASSOC);

    foreach ($resRecits as $r){
        $recitID = $r['id'];
        $recitTitre = $r['titre'];

        $reqChapitres = $db->query('SELECT id, titre_chapitre FROM chapitres WHERE recit_id = '.$r['id'].'');
        $resChapitres = $reqChapitres->fetchAll(PDO::FETCH_ASSOC);

        foreach ($resChapitres as $c){
            $chapTitre = $c['titre_chapitre'];
        }

        $arr = array('titre'=>$recitTitre,'chapitre'=>$chapTitre);
        echo json_encode($arr, JSON_UNESCAPED_UNICODE);
    }

}else{
    echo "bdd non connectée.";
}
?>

I tested the method proposed here, but the result is worse. I don't know what to do :(

Thanks for your help!

Upvotes: 4

Views: 2037

Answers (3)

Tasnuva Tavasum oshin
Tasnuva Tavasum oshin

Reputation: 4750

>  For Me this is Worked !


 <?php
    header('content-type: application/json');
    date_default_timezone_set('Asia/Dhaka');
    $DatabaseName = "";
    $HostPass = "";
    $HostUser = "";
    $HostName = "LocalHost";
    $db_connect = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

    $userid = $_GET['id'];
    $status = $_GET['status'];
    $rows = array();
    $datas = array();

    $result = mysqli_query($db_connect, "SELECT id FROM drivers WHERE phone = '$userid'");
    if ($result)
    {
        $row = mysqli_fetch_assoc($result);
        $id = $row['id'];

        $result = mysqli_query($db_connect, "SELECT `delivery_id` , `date`, `time` FROM `driver_orders` WHERE driver_id='$id' AND `status` ='$status'");
        mysqli_set_charset($db_connect,"utf8");
        while ($row = mysqli_fetch_assoc($result))
        {

            $d_id = $row['delivery_id'];

            $data = mysqli_query($db_connect, "SELECT r_name,r_number,r_zone,r_address,amount FROM deliveries  WHERE id = '$d_id'");
            while ($row2 = mysqli_fetch_assoc($data))
            {
                $datas[] = array(
                    "r_name" => $row2['r_name'],
                    "delivery_id" => $row['delivery_id'],
                    "time"=> $row['time'],
                    "date"=> $row['date'],
                    "r_number" => $row2['r_number'],
                    "r_zone" => $row2['r_zone'],
                    "amount" => $row2['amount'],
                    "r_address" => $row2['r_address']

                );

            }



        }

    }

    echo json_encode($datas);

    ?>

Upvotes: 0

nvanesch
nvanesch

Reputation: 2600

<?php
session_start();
require_once('connexion_db.php');

if($db=connect()){
    $userID = $_SESSION['id'];

    $arr = array();

    $reqRecits = $db->query('SELECT titre, id FROM recits WHERE user_id = '.$userID.'');
    $resRecits = $reqRecits->fetchAll(PDO::FETCH_ASSOC);
    $chapTitres = array();
    foreach ($resRecits as $r){
        $recitID = $r['id'];
        $recitTitre = $r['titre'];

        $reqChapitres = $db->query('SELECT id, titre_chapitre FROM chapitres WHERE recit_id = '.$r['id'].'');
        $resChapitres = $reqChapitres->fetchAll(PDO::FETCH_ASSOC);


        foreach ($resChapitres as $c){
            $chapTitres[] = $c['titre_chapitre'];
        }



        $arr[] = array('titre' => $recitTitre, 'chaptitres' => $chapTitres);
    }

    echo json_encode($arr, JSON_UNESCAPED_UNICODE);

}else{
    echo "bdd non connectée.";
}
?>

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

It seems like you'd want the inner loop to go more like this:

$chapTitre = array();
foreach ($resChapitres as $c){
  $chapTitre[] = $c['titre_chapitre'];
}

So your resulting JSON would include all the chapter titles.

Also, as it stands, you're listing a series of unconnected JSON objects, which should probably be a single array to be a legal JSON object.

foreach ($resRecits as $r){
    $recitID = $r['id'];
    $recitTitre = $r['titre'];

    $reqChapitres = $db->query('SELECT id, titre_chapitre FROM chapitres WHERE recit_id = '.$r['id'].'');
    $resChapitres = $reqChapitres->fetchAll(PDO::FETCH_ASSOC);

    $chapTitre = array();
    foreach ($resChapitres as $c){
      $chapTitre[] = $c['titre_chapitre'];
    }

    $arr[] = array('titre'=>$recitTitre,'chapitre'=>$chapTitre);
}

echo json_encode($arr, JSON_UNESCAPED_UNICODE);

Will collect them all and output as a list.

[
  { 
    'titre': 'Title 1',
    'chaptitre': ['Chapter 1', 'Chapter 2']
  },
  { 
    'titre': 'Title 2',
    'chaptitre': ['Chapter 1', 'Chapter 2', 'Chapter 3']
  },
]

Upvotes: 2

Related Questions