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.
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);
}
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");
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;
}
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.
Is it possible to get a JSON output looks like with one query?
[{
"name": "Date",
"data": ["2013-01-01", "2013-02-01", "2013-03-01", "2013-04-01", "2013-05-01"] //data from grouped from_date column
}, {
"name": "KD",
"data": [4, 5, 6, 2, 5] // arrays from saldo_sprzedazy for KD sales_group
}, {
"name": "SG",
"data": [5, 2, 3, 6, 7] // arrays from saldo_sprzedazy for SG sales_group
}]
My current query:
SELECT
sales_raport_all.from_date,
SUM(sales_raport_all.saldo_sprzedazy),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date
I group by from_date but I need to also group by sales_group...
Is it possible to do this on the mysql table with I have?
i try to prepare data to Column Highcharts highcharts.com/demo/column-basic
EDIT:
OK, maybe this will clarify my earlier question :)
This is my PHP code:
$query = mysql_query("SELECT
sales_raport_all.from_date,
sales_raport_all.to_date,
sales_raport_all.konto,
SUM(sales_raport_all.saldo_sprzedazy),
SUM(sales_raport_all.wartosc_kosztowa),
SUM(sales_raport_all.marza),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date");
$category = array();
$category['name'] = 'Data';
while($r = mysql_fetch_array($query)) {
$category['data'][] = $r['from_date'];
}
$querySG = mysql_query("SELECT
sales_raport_all.from_date,
sales_raport_all.to_date,
sales_raport_all.konto,
SUM(sales_raport_all.saldo_sprzedazy),
SUM(sales_raport_all.wartosc_kosztowa),
SUM(sales_raport_all.marza),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
klienci_ax_all.sales_group = 'SG'
AND
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date");
$series1 = array();
$series1['name'] = 'SG';
while($r = mysql_fetch_array($querySG)) {
$series1['data'][] = intval($r['SUM(sales_raport_all.saldo_sprzedazy)']);
}
....
My question is: do I have to write a separate query for every specific sales_group or is there a simpler way?
Now I use json like this:
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series2);
array_push($result,$series3);
print json_encode($result);
If you want to do this in one go, you have to group by both sales_group and from_date:
$query = mysql_query("SELECT
sales_raport_all.from_date,
sales_raport_all.to_date,
sales_raport_all.konto,
SUM(sales_raport_all.saldo_sprzedazy),
SUM(sales_raport_all.wartosc_kosztowa),
SUM(sales_raport_all.marza),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date,
klienci_ax_all.sales_group
ORDER BY
sales_raport_all.from_date,
klienci_ax_all.sales_group");
Then collect all the possible dates and all the data in a raw array.
$raw = array();
$dates = array();
while ($r = mysql_fetch_array($query)) {
$date = $r['from_date'];
if (!in_array($date, $dates)) $dates[] = $date;
$sales_group = $r['sales_group'];
$raw[$sales_group][$date] = intval($r['SUM(sales_raport_all.saldo_sprzedazy)']);
}
Lastly go through the raw data, and check if on a given date the sales_group has relevant data or set it to zero.
$data = array();
$data[0] = array('name' => "Date", 'data' => $dates);
foreach ($raw as $name => $d) {
$new_data = array('name' => $name, 'data' => array());
foreach ($dates as $date) {
$new_data['data'][] = isset($d[$date]) ? $d[$date] : 0;
}
$data[] = $new_data;
}
The final $data will have the desired structure and all the data you need.