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.
Related
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);
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.
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);
?>
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 have this in php
$comment = array;
while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){
$comment[$row['name']] = $row['comment'];
}
echo json_encode($comment);
Having these results
{"John":"Yo","Dan":"Hello","May":"Bye"}
The problem is I actually have two comments(Zup,Yo) for John, but as you can see, it only displays the last comment of John which is "Yo". So I wanted the results of John to be
{"John":["Yo","Sup"]}
^ is this possible?
How can I do that? Im sorry still having a hard time dealing with JSON. Thanks
This is actually my full code
while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){
$comment[$row['name']] = $row['comment'];
$sql_dup = "SELECT name, COUNT(name) AS dup_count
FROM comment
GROUP BY name
HAVING (COUNT(name) > 1)
";
$sqlExec_dup = mysql_query($sql_dup, $connection);
$row_dup = mysql_fetch_array($sqlExec_dup, MYSQL_ASSOC);
if($row['name'] = $row_dup['name']){
$sql_dup2 = "SELECT * FROM comment WHERE name = '{$row['name']}'";
$sqlExec_dup2 = mysql_query($sql_dup2, $connection);
while($row_dup2 = mysql_fetch_array($sqlExec_dup2, MYSQL_ASSOC)){
$x += 1;
if($x <= $row_dup['dup_count']){
$comment[$row['name']][] = $row_dup2['comment'];
}
}
}
}
If the name has a duplicate, meaning it has more than one comment, still cant get my desired results.
You would have to check whether it already exists or not, and if it does, create an array (or do that from the start)
// Create arrays with names
$comment[$row['name']][] = $row['comment'];
or
// Check if there's an array
if (isset($comment[$row['name']])) {
if (is_array($comment[$row['name']])) {
$comment[$row['name']][] = $row['comment'];
} else {
$comment[$row['name']] = array($comment[$row['name']], $row['comment']);
}
} else {
$comment[$row['name']] = $row['comment'];
}
I should point out that the first solution would be very much preferred because it is a lot more consequent.
Yes, it is possible, but you need to do some preprocessing for that:
$comment = array;
while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){
if(!isset($comment[$row['name']])) {
$comment[$row['name']] = array();
}
$comment[$row['name']][] = $row['comment'];
}
echo json_encode($comment);
Yes, it's possible. Instead of this line:
$comment[$row['name']] = $row['comment'];
Use this:
$comment[$row['name']] = array('Yo', 'Sup');
And replace the contents of the array with the greetings you want from the database.
Simple change:
$comment[$row['name']] = $row['comment'];
to
$comment[$row['name']][] = $row['comment'];
Each name element of the $comment array was being overwritten each time the same name came up.