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!
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']
},
]
<?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.";
}
?>
> 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);
?>
Related
I beginner to Amchart and am test load data in Amchart using php
this is my format json
[{"date":"2018-01-01","column-1":"5187"},{"date":"2018-01-02","column-1":"15790"},{"date":"2018-01-03","column-1":"15826"},{"date":"2018-01-04","column-1":"17026"},{"date":"2018-01-05","column-1":"17908"},{"date":"2018-01-01","column-2":"2143"},{"date":"2018-01-02","column-2":"6192"},{"date":"2018-01-03","column-2":"6106"},{"date":"2018-01-04","column-2":"6532"},{"date":"2018-01-05","column-2":"7000"}]
and this is my code
var data1 = <?php
include('connect.php');
$data = array();
$arr = array();
$query = "SELECT * FROM shell_table_graph";
$db = mysql_query($query);
while($rows = mysql_fetch_assoc($db)) {
$data[] = ['column' => $rows['column'], 'formula' => $rows['calculation']];
}
foreach($data as $rowss) {
$formula = $rowss['formula'];
$query = "SELECT Date, SUM(".$formula.") AS Formula FROM eod_split_interval WHERE Date BETWEEN '2018-01-01' AND '2018-01-05' GROUP BY Date";
$db = mysql_query($query);
while($r = mysql_fetch_assoc($db)) {
$arr[] = ['date' => $r['Date'], $rowss['column'] => $r['Formula']];
$code = json_encode($arr);
}
}
echo $code;
?>;
/*mysql table admin
id=1, user_name = mike
id=2, user_name = sam*/
$user_name_query = mysql_query("select id, user_name from admin");
$user_name_array = array();
while ($row = mysql_fetch_array($user_name_query)) {
$user_name_array[] = array('user' => $row['user_name']);
}
foreach($user_name_array as $key => $record){
$record_values .= "{$record['user']},";
}
$record_values = substr($record_values, 0, -1);
// $record_values is: mike,sam
$userThatHaveThePermission = array($record_values);
if (in_array(mike, $userThatHaveThePermission)){
echo "do something"
}
my question is about the values of variable $record_values this variable not working in: $userThatHaveThePermission = array($record_values);
If I add the user names(mike,sam) to $userThatHaveThePermission = array(mike,sam); everything working fine, WHY? did I miss something.
I think you are beginner in php-mysql. I would refactor your code for you.
$user_name_query = mysql_query("select id, user_name from admin");
$user_name_array = [];
while ($row = mysql_fetch_array($user_name_query)) {
$user_name_array[] = $row['user_name'];
}
$userThatHaveThePermission = $user_name_array;
if (in_array('mike', $userThatHaveThePermission)){
echo "do something";
}
But take advice of the people commenting on your status. Do not use mysql_query. Use some framework.
I need to display categories and its sub categories in json format, here problem is each category has unlimited levels, some categories has 4 levels and some 2 and some 3 levels. I have tried one solution it is showing only one under level, but I need to show all levels.
Table schema:
Code Example:
function categories() {
header('Content-Type: application/json');
$sql = "select id,name,parent_id from categories where parent_id = 0";
$q = $this->db->conn_id->prepare($sql);
$q->execute();
$main_cat = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$sql2 = "select id,name,parent_id from categories where parent_id = ?";
$sub_cat = array();
$r = $this->db->conn_id->prepare($sql2);
$r->bindParam(1, $row['id']);
$r->execute();
while ($row1 = $r->fetch(PDO::FETCH_ASSOC)) {
array_push($sub_cat, array_filter($row1));
}
$row['subcategories'] = $sub_cat;
array_push($main_cat, array_filter($row));
}
echo json_encode(array("categories" => $main_cat));
}
Above Code Json Response Example:
{"categories":[{"id":"1","name":"Development","subcategories":[{"id":"2","name":"All Development","parent_id":"1"},{"id":"3","name":"Web Development","parent_id":"1"},{"id":"12","name":"Mobile Apps","parent_id":"1"}]},{"id":"4","name":"Design","subcategories":[{"id":"5","name":"All Design","parent_id":"4"}]},{"id":"11","name":"IT & Software"}]}
Any one can help me how to solve this issue.
I have tried this solution works for me.
function categories() {
$sql = "SELECT * FROM categories where parent_id = 0";
$results = $this->db->conn_id->prepare($sql);
$results->execute();
while ($result = $results->fetch(PDO::FETCH_ASSOC)) {
$subcat = array();
$id = $result['id'];
$childs = $this->hasChilds($id);
$categories[] = array("id" => $result['id'], "name" => $result['name'], "parent_id" => $result['parent_id'], "subcats" => array_filter($childs));
}
echo json_encode($categories);
}
function hasChilds($id) {
$sql = "SELECT * FROM categories where parent_id = ? ";
$results = $this->db->conn_id->prepare($sql);
$results->bindParam(1, $id);
$results->execute();
$count = $results->rowCount();
$array = array();
if ($count > 0) {
while ($result = $results->fetch(PDO::FETCH_ASSOC)) {
$array[] = array("id" => $result['id'], "name" => $result['name'], "parent_id" => $result['parent_id'], "subcats" => array_filter($this->hasChilds($result['id'])));
}
} else {
$array[] = null;
}
return $array;
}
The problem I have is when I echo or print the following variables, the data I receive is that of the last business listed in my table only.
At present no matter the listing I click I get the same set of data for the last business returned.
As you can see in the below code I am passing the business_name from the clicked listing to be used in my query to find the relevant business profile information.
$business_name = mysql_real_escape_string($_GET['business_name']);
$query = "SELECT
business_id,
category,
years_recommended,
profile_size,
business_name,
established,
employees,
service,
strengths,
ideal_for,
reassurance
FROM
business_data
WHERE
business_name = '$business_name'
AND
profile_size = 'A'
OR
profile_size = 'B'
OR
profile_size = 'C'
OR
profile_size = 'D'
OR
profile_size = 'E'";
$result = mysql_query($query, $dbc)
or die (mysql_error($dbc));
while($row = mysql_fetch_array($result)) {
$business_id = $row["business_id"];
$profile_size = $row["profile_size"];
$category = $row["category"];
$years = $row["years_recommended"];
$established = $row["established"];
$employees = $row["employees"];
$service = $row["service"];
$strengths = $row["strengths"];
$ideal_for = $row["ideal_for"];
$reassurance = $row["reassurance"];
}
echo...
If you need more information please let me know.
Is there anything wrong with my code?
Many thanks in advance.
Your echo call is outside the fetch loop, so you'll only see the last result even though the others were returned.
while($row = mysql_fetch_array($result)) {
$business_id = $row["business_id"];
$profile_size = $row["profile_size"];
$category = $row["category"];
$years = $row["years_recommended"];
$established = $row["established"];
$employees = $row["employees"];
$service = $row["service"];
$strengths = $row["strengths"];
$ideal_for = $row["ideal_for"];
$reassurance = $row["reassurance"];
// Echo **inside** the loop
echo...
}
If you wish, you can store all the results in a large array, which can then be used anywhere subsequently in your script, as many times as needed:
// Array for all results
$results = array();
while($row = mysql_fetch_array($result)) {
// Append each row fetched onto the big array
$results[] = $row;
}
// Now use it as needed:
foreach ($results as $r) {
echo $r['profile_size'];
print_r($r);
}
your echo should be inside the loop
I am currently using a JSON encoded array to display the users in my database for an auto-suggest feature.
It looks something like this:
$sth = mysql_query("SELECT id, name FROM users");
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
$data[] = $json;
}
print json_encode($data);
This returns:
[{"id":"81","name":"John Doe"},{"id":"82","name":"Jane Doe"}]
My question is somewhat 2-fold:
First, how would I manually add an additional object to this output? For example, let's say I wanted to add: {"id":"444","name":"A New Name"}
Thus, it'd look like:
[{"id":"81","name":"John Doe"},{"id":"82","name":"Jane Doe"},{"id":"444","name":"A New Name"}]
Second, let's say I also wanted to add more objects to the array from a separate table as well, such as:
$sth = mysql_query("SELECT id, title FROM another_table");
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['title'];
$json['id'] = $row['id'];
$data[] = $json;
}
print json_encode($data);
This way I could have both tables populated in the JSON array, thus, showing up as additional options in my autosuggest.
Hopefully this makes sense, as I've tried hard to articulate what I am trying to accomplish.
Thanks!
Just keep pushing to the $data array.
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
$data[] = $json;
}
$custom = array('name'=>'foo', 'id' => 'bar');
$data[] = $custom;
Then at the very end, do your json_encode. Assuming you're not referring to merging it in the JS itself with multiple ajax calls.
And if you have separate scripts, combine them in one php page.
Try in this way:-
$temp = json_encode($json); //$json={"var1":"value1","var2":"value2"}
$temp=substr($temp,0,-1);
$temp.=',"variable":"'.$value.'"}';
You could edit the JSON (text), but it's much easier to modify the array before you encode it.
Or am I missing something?
I'm not an expert in any of these fields, but I'll try and see if I can help. Try one of these:
Option 1 (I don't know how unions work in mysql):
$sth = mysql_query("SELECT id, name FROM users union SELECT id, name FROM (SELECT id, title as name from another_table) as T2");
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
}
$json['name'] = 'A new name';
$json['id'] = '444';
$data[] = $json;
print json_encode($data);
I've never done PHP, so I'm making assumptions. I've also never used MySql, so there's more assumptions.
Option 2:
$sth = mysql_query("SELECT id, name FROM users");
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
}
$sth = mysql_query("SELECT id, title from another_table");
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['title'];
$json['id'] = $row['id'];
}
$json['name'] = 'A new name';
$json['id'] = '444';
$data[] = $json;
print json_encode($data);
Hope this helps.