php - Insert results of multiple tables into one json_encode() -


excuse language mistakes, speak french.

i did research on site , elsewhere, have found didn't solve problem.

i doing site people can post stories. i'm working on page author should able see stories , chapters of each of them.

i query on 2 tables titles of stories , chapters. have table "stories" in there title , summary of each story (and other stuff id , date of publication). , table called "chapters", in there title of each chapter , id of story belong.

i retrieve these items later in html, have this:


story title 1

chapter 1

chapter 2


so json_encode () jsonlint said json invalid. php new me, began learn i'm not writing code correctly.

here code:

<?php session_start(); require_once('connexion_db.php');  if($db=connect()){     $userid = $_session['id'];      $arr = array();      $reqrecits = $db->query('select titre, id recits user_id = '.$userid.'');     $resrecits = $reqrecits->fetchall(pdo::fetch_assoc);      foreach ($resrecits $r){         $recitid = $r['id'];         $recittitre = $r['titre'];          $reqchapitres = $db->query('select id, titre_chapitre chapitres recit_id = '.$r['id'].'');         $reschapitres = $reqchapitres->fetchall(pdo::fetch_assoc);          foreach ($reschapitres $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 method proposed here, result worse. don't know :(

thanks help!

it seems you'd want inner loop go more this:

$chaptitre = array(); foreach ($reschapitres $c){   $chaptitre[] = $c['titre_chapitre']; } 

so resulting json include chapter titles.

also, stands, you're listing series of unconnected json objects, should single array legal json object.

foreach ($resrecits $r){     $recitid = $r['id'];     $recittitre = $r['titre'];      $reqchapitres = $db->query('select id, titre_chapitre chapitres recit_id = '.$r['id'].'');     $reschapitres = $reqchapitres->fetchall(pdo::fetch_assoc);      $chaptitre = array();     foreach ($reschapitres $c){       $chaptitre[] = $c['titre_chapitre'];     }      $arr[] = array('titre'=>$recittitre,'chapitre'=>$chaptitre); }  echo json_encode($arr, json_unescaped_unicode); 

will collect them , output list.

[   {      'titre': 'title 1',     'chaptitre': ['chapter 1', 'chapter 2']   },   {      'titre': 'title 2',     'chaptitre': ['chapter 1', 'chapter 2', 'chapter 3']   }, ] 

Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -