How can I add a custom key value pair to the existing SQL result?
<?php
require_once "dbaccess.php";
$json = array();
$access = new DatabaseAccess();
$sql = $access->Connect();
$stmt = $sql->prepare("select * from people");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $key => $value){
$json[$key] = $value;
};
echo json_encode($json, JSON_UNESCAPED_SLASHES);
?>
The current JSON result is :
[
{
"id": "1",
"first_name": "James",
"last_name": "Haze"
},
{
"id": "2",
"first_name": "Neo",
"last_name": "Anderson"
}
]
How can I add to the current elements "country": "Australia" without modifying MySQL database? I want the result to look like this:
[
{
"id": "1",
"first_name": "James",
"last_name": "Haze",
"Country": "Australia"
},
{
"id": "2",
"first_name": "Neo",
"last_name": "Anderson",
"Country": "Australia"
}
]
Is it possible?
You can just select the additional "columns" you want in your SQL:
$stmt = $sql->prepare("select
id
, first_name
, last_name
, 'Australia' as Country
from people");
As an aside, you shouldn't use * in your select queries - that makes them behave weird when you add new column names and hides errors when you rename a column.
If you want to select a variable value, you can do that by interpolating it into your SQL directly:
$stmt = $sql->prepare("select
id
, first_name
, last_name
, '$country_name' as Country
from people");
Even though it is not necessary for country names, it is still a good practice to use (named) SQL placeholders, so you really should be doing it as:
$stmt = $sql->prepare("select
id
, first_name
, last_name
, :country as Country
from people");
$stmt->execute([':country' => $country_name]);
(This is mostly when reusing this code elsewhere, as I'm unaware of valid country names that contain single quotes)
you could add the values you need directly in select
$stmt = $sql->prepare("select id
, firt_name
, last_name
, 'Australia' AS country
from people");
Related
I have create the json file from the sql table but the output is not same with the output i expected. Below is my code to create the json file from the sql table
<?php
include 'config.php';
$sql = "SELECT table_id, table_name,GROUP_CONCAT(price) price FROM tables INNER JOIN table_orders ON table_id = res_table_id GROUP BY table_id";
$result = mysqli_query($mysqli,$sql);
while($data1 = $result->fetch_assoc()){
$data[] = $data1;
}
$encoded_data = json_encode($data,JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
file_put_contents('data_json',$encoded_data);
?>
The output will look like this
[
{
"table_id": "1",
"table_name": "Table 1",
"price": "20.00,15.00,7.90"
},
{
"table_id": "2",
"table_name": "Table 2",
"price": "7.90,15.00"
}
]
I want my result something like the output below:
{"table":[
{
"table_id": "1",
"table_name": "Table 1",
"price": [
"20.00","15.00","7.90"
]
},
{
"table_id": "2",
"table_name": "Table 2",
"price": [
"7.90","15.00"
]
}
]}
<?php
include 'config.php';
$sql = "SELECT table_id, table_name,GROUP_CONCAT(price) price FROM tables INNER JOIN table_orders ON table_id = res_table_id GROUP BY table_id";
$result = mysqli_query($mysqli,$sql);
$data = [];
while($data1 = $result->fetch_assoc()){
$data1['price'] = explode(',', $data1['price']);
$data[] = $data1;
}
$encoded_data = json_encode(['table' => $data], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
file_put_contents('data_json', $encoded_data);
What this does:
In your initial loop, you first format your array items in the way you want. Then you can format your JSON string in the nested structure you want by passing in the format you like.
There are a few ways to optimize this, but that's the gist of it.
$my_new_data = [];
while($data1 = $result->fetch_assoc()){
array_push($my_new_data, $data1);
}
I've 2 tables, I want to get data from the first one depends on "id", and the data from second one depends on the "gid" that same as "id" from the first table, in JSON.
Example:
First Table:
- - - - - - -
id name
1 Aaron
2 Caleb
3 Albert
4 Ethan
Second Table:
- - - - - - -
id gid image
1 1 http://.......image1.jpg
2 1 http://.......image2.jpg
3 2 http://.......image3.jpg
4 3 http://.......image4.jpg
5 3 http://.......image5.jpg
6 3 http://.......image6.jpg
I want the result when I request id=1, Something like this:
"names": [
{
"id": 1,
"name": "Aaron"
"images":[
{
"id" :1
"url":http://.......image1.jpg
},
{
"id" :2
"url":http://.......image2.jpg
}
]
}
]
This some of my code:
$SqlInfo = "Select * from tabel1 where id='$id'";
$obj = json_decode($_GET["x"], false);
$stmt = $con->prepare($SqlInfo);
$stmt->bind_param("ss", $obj->table, $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode(array(
'status' => 'Ok',
'name' => $outp
));
to be more specific, my above code , bring json format for the first table, I want to insert the result of the second table in the same result of json (of the first table).
Thank you ...
first you can use inner join to combine result from both table
$sql = "select
t2.gid,
t2.id,
t2.image,
ti.name
from
second_table as t2
join first_table as t1 on t2.gid = t1.id
where id='$id'
";
$obj = json_decode($_GET["x"], false);
$stmt = $con->prepare($SqlInfo);
$stmt->bind_param("ss", $obj->table, $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(PDO::FETCH_ASSOC);
/*PDO::FETCH_ASSOC return result in associative array */
$arr = array();
if(!empty($outp)){
$i =1;/* this is used so that first table data can only be feed to array once*/
foreach($outp as $val){
if($i ==1){
$arr['id'] = $val['gid'];
$arr['name'] = $val['name'];
}
$tmp = array();
$tmp['id'] = $val['gid'];
$tmp['url'] = $val['image'];
$arr['images'][] = $tmp;
$i++;
/*increment $i so that we cannot enter $val['name'] repeatedly*/
}
}
$json_arr = array('status' => 'Ok','name' => $arr);
echo json_encode($json_arr);
First, you need the result of first table to decode into Array.
$first_table = array(
'0'=> ['id'=> 1, 'name' =>'Aaron' ],
'1'=> ['id'=> 2, 'name' =>'Caleb' ],
'2'=> ['id'=> 3, 'name' =>'Albert'],
'3'=> ['id'=> 4, 'name' =>'Ethan' ]
);
//create function to retrieve images by ID from Second Table
function get_images($id)
{
$SqlInfo = "Select id, image as url from tabel2 where gid='$id'";
$stmt = $con->prepare($SqlInfo);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
return $outp;
}
// create a new object
$new_array=array();
//Loop first table
foreach ( $first_table as $key => $value){
$new_array[$value['name']] = [
'name' => $value['name'],
'id' => $value['id'],
'images' => get_images($value['id']) // Get images from function
];
}
$final = json_encode($new_array);
This was not tested, but solution should be in this direction
I have this php code to get all payments (payment amount, the name of the user, the month of the payment) deposited by all users in all months:
$result = $mysqli->query("SELECT p.id as id, p.amount as amount,
u.name as user_id, m.name as month_id
FROM payment p, user u, month m
WHERE p.user_id = u.id AND p.month_id = m.id;");
//Add all records to an array
$rows = array();
while($row = $result->fetch_array())
{
$rows[] = $row;
}
//Return result
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
And this is the json I get:
[{
"Result": "OK",
"Records": [
{
"0": "1",
"id": "1",
"1": "250",
"amount": "250",
"2": "user 1",
"user_id": "user 1",
"3": "jan 15",
"month_id": "jan 15"
},
...]
Now, I think these "0", "1", "2", "3" names/values are not supposed to be there and I must have done something wrong here. Is this the doing of the json_encode()? Or is it the way I'm querying the db?
Thanks for the help!
The issu here is that you are calling fetch_array().
fetch_array() will return an array of index based values as well as key based values. So if you only want the key(name) based values in the array, use the below code.
Try fetch_assoc().
$rows = array();
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
Or fetch_array(MYSQLI_ASSOC)
$rows = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$rows[] = $row;
}
I want to create a json string from two table's queries in one to many relations. I have done like this
$query = "SELECT id,name FROM sample1 ORDER BY id ASC" ;
$result = mysql_query($query) or die(mysql_error());
$parent = array() ;
while($row = mysql_fetch_array($result))
{
$parent[]= array("id"=>$row['id'],"name"=>$row['name']);
$query1 = "SELECT id,cid,cmessage FROM sample2 WHERE id = '$row[id]' ORDER BY cid ASC" ;
$result1 = mysql_query($query1) or die(mysql_error());
while($row1 = mysql_fetch_array($result1))
{
$parent[] = array("id"=>$row1['id'],"cid"=>$row1['cid'],"comment"=>$row1['cmessage']);
}
} echo json_encode($parent);
it shows an output like this [{"id":"1","name":"Arathy"},{"id":"1","cid":"11","comment":"hai"},{"id":"1","cid":"111","comment":"exe"},{"id":"2","name":"Dhanya"},{"id":"2","cid":"22","comment":"yes"}]
But I want the format like as shown below ,
[
{
"id": "1",
"name": "Arathy",
"details": [
{
"id": "1",
"cid": "11",
"comment": "hai"
},
{
"id": "11",
"cid": "111",
"comment": "exe"
}
]
},
{
"id": "2",
"name": "Dhanya",
"details": [
{
"id": "2",
"cid": "22",
"comment": "yes"
}
]
} ]
Please help to correct
It will be something like,
while($row = mysql_fetch_array($result))
{
$parent[$row['id']]= array("id"=>$row['id'],"name"=>$row['name']);
$query1 = "SELECT id,cid,cmessage FROM sample2 WHERE id = '$row[id]' ORDER BY cid ASC" ;
$result1 = mysql_query($query1) or die(mysql_error());
while($row1 = mysql_fetch_array($result1))
{
$parent[$row['id']]["details"][] = array("id"=>$row1['id'],"cid"=>$row1['cid'],"comment"=>$row1['cmessage']);
}
}
echo json_encode($parent);
Warning: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
This question already has an answer here:
Optimize while and SQL in foreach
(1 answer)
Closed 8 years ago.
My code is :
$text = '12-10-4-32-45-name-sara-x-y-86';
$array = explode('-',$text);
foreach($array as $value) {
$sql = mysql_query("SELECT * FROM `table` WHERE `pid`='$value' ORDER BY `id` LIMIT 3");
while($row = mysql_fetch_array($sql)) {
echo $row['title'];
echo '';
}
echo '';
}
This code work full but if in $text use 150 variable , server down !
How optimize this code for most variable ?!
Thx
If you need all of them as ids (which includes a string which is weird). Consider this example:
$text = '12-10-4-32-45-name-sara-x-y-86';
$text = array_unique(explode('-', $text)); // just in case there are duplicate ids
$statement = 'SELECT * FROM `table` WHERE `pid` IN("'.implode('", "', $text).'") ORDER BY `id` LIMIT 3';
// should be like this
// SELECT * FROM `table` WHERE `pid` IN("12", "10", "4", "32", "45", "name", "sara", "x", "y", "86") ORDER BY `id` LIMIT 3
// then just continue on your mysql_query
$sql = mysql_query($statement);
while($row = mysql_fetch_assoc($sql)) {
// print your values or whatever it is you need to do
// echo $row['title'];
}
Note: You don't need to query each value, that would be a total waste of resources. Imagine your text has (as you said) 150 numbers. Try to use the IN() of mysql so that it just make a single trip of query.