Json pass various fliends on json array - php

I have this code that fetches some fields from MYSQL database. The problem is that the php appears plain white. But if I delete elements of while and leave only one , the array prints fine.
$sql = "SELECT rest.img,rest.rest_name,horario.desc_hor, rest.descp, rest.rest_id FROM rest, type, horario WHERE rest.type_id = type.type_id AND rest.id_hor = horario.id_hor AND rest.type_id=1";
$result = $conn->query($sql);
$cnt = $result->num_rows;
$json = array();
if($cnt>0){
while($row = $result->fetch_assoc()){
$json['']=$row['img'];
$json['']=$row['rest_name'];
$json['']=$row['desc_hor'];
$json['']=$row['descp'];
$json['']=$row['rest_id'];
}
}
print( json_encode($json));

The problem with your code is that you are not assigning indexes automatically. You are always assigning the index [''] for all columns and rows in the array.
Try this...
$json = array();
while($row = $result->fetch_assoc()){
array_push($json, $row);
}
echo json_encode($json);
or this...
$json = array();
while($row = $result->fetch_assoc()){
$json[] = $row;
}
echo json_encode($json);
Of either ways, will generate the automátic indexes in the array.

Related

Printing multiple table queries using json_encode in php

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?
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);

How to get entire column from database and store it in an array using php?

My table's name is userdetails, it has four attributes named name, username, mobile and password. I want to get all the mobile numbers and store it in an array using php.
I have used the following php code
if($_SERVER['REQUEST_METHOD']=='GET'){
require_once('dbConnect.php');
$mobile = $_GET['mobile'];
$sql = "SELECT MOBILE FROM USERDETAILS";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"MOBILE"=>$res['MOBILE']
)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
but all I am getting is the first entry of the database.
Please help.
You should loop through the records by doing the following:
$result = [];
while ($array = mysqli_fetch_array($r)) {
$result[] = $array['MOBILE'];
}
echo json_encode($result);
For getting all number of column use while loop as
$jsonData = array();// initialized you array
while ($array = mysqli_fetch_array($r,MYSQLI_ASSOC)) {// add MYSQLI_ASSOC to get associative array
$jsonData[] = $res['MOBILE'];// store data into array
}
echo json_encode($jsonData);// convert in into json
Try this:
$result = mysqli_query($con,$sql);
$mob = Array();
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$mob[] = $row['MOBILE'];
}

how to get an array of objects from sql query

My code is
$sql = 'select * from table;' $res = $connection->query($sql);
while($row = mysqli_fetch_row($res){'tackle output'};
to get an object
while($row = $res->fetch_object()){'tackle output'};
Question: what do I have to do to get an array of objects, so my output is thus
$data[$row[0]]= fetch_object();
try this one:
$data = array();
while($row = $res->fetch_object()){
$data[] = $row;
}
Use it like
$data = array();
while($row = $res->fetch_object()){
$data[$row->id] = $row;
}
may you want to fetch all
you can do this by
http://php.net/manual/en/mysqli-result.fetch-all.php

Convert mysql select results to json (array of arrays)

I need to encode a table content to JSON in order to insert it into a file.
The output has to be as following :
{
"name1":[{"id":"11","name":"name1","k1":"foo","k2":"bar"}],
"name2":[{"id":"12","name":"name2","k1":"foo","k2":"bar"}],
}
Indeed, each JSON "line" corresponds to the content of the mysql row and the name of each JSON array is the name of the 'name' column.
The only thing I could manage for the moment is this :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
$index = 0;
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$index] = $row;
$index++;
}
echo json_encode($return_arr);
And here is the output I get :
[
{"id":"11","name":"name1","k1":"foo","k2":"bar"},
{"id":"12","name":"name2","k1":"foo","k2":"bar"},
]
Thanks a lot !!!
UPDATED
Working code :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$return_arr[ $row['nom_appart'] ][] = $row;
}
echo json_encode($return_arr);
}
You were close. I noticed you want final output to be an object not an array, because the outer brackets are {} not []. So you need a different object type, and you need to use each row's name as the key for storing that row.
$return_obj = new stdClass();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
$return_obj->$name = [$row]; // for PHP < 5.4 use array($row)
}
echo json_encode($return_obj);
This loop is enough, to create the desired JSON:
$return_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$row['name']][] = $row; #or $return_arr[$row['name']] = [$row];
}
echo json_encode($return_arr);
I was working on it a lot of time and Create mash/mysql-json-serializer package.
https://github.com/AndreyMashukov/mysql-json-serializer
You can select Json_array of json_objects and etc. It support ManyToMany, oneToMany, manyToOne relations
SELECT JSON_ARRAYAGG(JSON_OBJECT('id',est_res.est_id,'name',est_res.est_name,'advert_groups',(SELECT JSON_ARRAYAGG(JSON_OBJECT('id',adg.adg_id,'name',adg.adg_name)) FROM advert_group adg INNER JOIN estate est_2 ON est_2.est_id = adg.adg_estate WHERE est_2.est_id = est_res.est_id))) FROM (SELECT * FROM estate est LIMIT 1 OFFSET 2) est_res
<?php
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$return_arr[] = $row;
}
echo json_encode($return_arr);
?>

Add Additional Objects to JSON Encoded Array

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.

Categories