How to create a json like this in php;
[{"idorder":"34",
"totalOrder":"55",
"products":[{"idproduct":"5","price":"10"},{"idproduct":"4","price":"45"}]
}]
from table mysql;
+---------+-----------+--------------+
| idorder | idproduct | priceproduct |
+---------+-----------+--------------+
| 1 | 4 | 45 |
| 1 | 5 | 10 |
+---------+-----------+--------------+
my current code something.php;
...
$result = $conn->query($pendientesq);
$return_arr = array();
$productos = array();
$r1=$result->fetch_array();
$return_arr['idorder'] = $r1['idorder'];
$return_arr['totalOrder'] = '55';
//But now????How to create sub array with multiples products.
echo json_encode($return_arr);
you need to try something like this:
$r1=$result->fetch_array();
$return_arr['idorder'] = $r1['idorder'];
$return_arr['totalOrder'] = '55';
// suposse total products are 10
$product=10;
for($i=0;$i<product;$i++){
$return_arr['product'][] = array("idproduct"=>$i,"price"=>$i);//use your price and idproduct.
}
echo json_encode($return_arr);
I don't know how Your table looks like because You've not described it.
But I got for example "orders" table with idorder,idproduct,priceproduct fields.
And wrote this code:
// $q = "SELECT * FROM orders WHERE idorder = 5"; // for single order
$q = "SELECT * FROM orders";
$result = $conn->query($q);
$orders = [];
while($record=$result->fetch_array()) {
if(!isset($orders[$record['idorder']])) {
$orders[$record['idorder']] = [];
$orders[$record['idorder']]['idorder'] = $record['idorder'];
$orders[$record['idorder']]['totalOrder'] = 0;
$orders[$record['idorder']]['products'] = [];
}
$orders[$record['idorder']]['products'][] = ['idproduct' => $recrod['idproduct'],
'price' => $record['priceproduct']];
$orders[$record['idorder']]['totalOrder'] += $record['priceproduct'];
}
$orders = array_values($orders);
echo json_encode($orders);
Related
I have a MySQL table with multiple columns, from which I need to select all of them of each record, and to create a specific $key=>$value from it.
for example
TABLE
ID | group_cat | group_sec | group_name | enabled | sent
-------------------------------------------------------------------------------------
1 | C | sct_a | Project_A | 1 | no
2 | C | sct_b | Project_B | 1 | no
3 | P | sct_c | Moderators | 1 | no
4 | C | sct_d | Ambassad | 1 | no
5 | P | sct_e | PMP | 0 | no
The MySQL query I need is "SELECT * FROM groups WHERE sent = 'no' "
By PHP is
PHP Code
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $key => $value) { $$key = $value; }
...
...
...
}
Here my question:
I need that the $key is from the column 'group_sec' and the related $value is from the column 'group_name'. So that the couple $$key=>$value can return this result (for instance)
echo $sec_b;
returns: Project_B
Could you help me to get this done please?
Thank you in advance
This will do the job for you:
${$row['group_sec']} = $row['group_name'];
echo $sct_b;
Output:
Project_B
You would use this in your while loop (the foreach can probably be deleted):
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
${$row['group_sec']} = $row['group_name'];
...
// do something with $sct_b
...
}
Alternatively, if your column names might change, but the positions will stay the same, you can use
while($row = $sth->fetch(PDO::FETCH_NUM)) {
${$row[2]} = $row[3];
...
// do something with $sct_b
...
}
You can build an array based on key and value you prefer using $row['group_sec'] for key and $row['group_name'] eg:
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$myArray[$row['group_sec']] = $row['group_name'];
}
and you can see the result
foreach($myArray as $key => $value){
echo $key . ' - ' . $value . '<br>';
}
$sql = "SELECT * FROM groups WHERE sent= 'no'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$list=[];
while($row = $result->fetch_assoc()) {
$list{$row['group_sec']} = $row['group_name'];
}
}
I have a dynamic form which have dynamic input of textbox and variable of date,float and time.I want to insert those input dynamically into my sql table.
So here is the part of my code.I'm only able to loop through one variable,When i want to loop through the time and float,it face the conversion problem on float and time.(If any picture needed just let me know )
$ct = 0;
if ($_POST['Dates'] && $_POST['slct']) {
foreach ($_POST['Dates'] as $value) {
$values = $value;
$dates = $_POST['Dates']; // for leave date
$datess = $_POST['datess']; // for created date
$Area = $_COOKIE['cooAreaCode'];
$days = $_POST['slct'];
$time = date("h:i a", strtotime($frtime));
$times = date("h:i a", strtotime($totime));
$frtime = $_POST['frtime'];
$totime = $_POST['totime'];
$link_mssql = odbc_connect(DB_HSATTEND, DB_USER, DB_PASS);
$sql = "SELECT MAX(RefNo) as val from tblLeaveHeader";
$res = odbc_exec($link_mssql, $sql);
while (odbc_fetch_row($res)) {
$count = odbc_result($res, "val");
}
odbc_free_result($res);
$temp = sprintf('%08d', $count + 1);
if (empty($_POST['frtime']) && empty($_POST['totime'])) {
$sql3 = "INSERT INTO tblLeaveDetails (RefNo, LeaveType, Leavedd, Leaveday, LeaveFrmTime, LeaveToTime)
VALUES('$temp','$Leave','$values', '$days[$ct]', NULL, NULL)";
$res = odbc_exec($link_mssql, $sql3);
$ct++;
} else {
$sql2 = "INSERT INTO tblLeaveDetails (RefNo, LeaveType, Leavedd, Leaveday, LeaveFrmTime, LeaveToTime)
VALUES('$temp','$Leave','$values', '$days[$ct]', '$frtime[$ct]', '$totime[$ct]')";
$res = odbc_exec($link_mssql, $sql2);
$ct++;
}
}
}
Example of result in sql table
| ID | Refno | Leavetype | Leaveday | Leavdd |frtime|totime
| 1 | 00001 | Annual Leave | 1 | 2017-07-17 |3.00 | 7.00
| 2 | 00001 | Annual Leave | 1 | 2017-07-18 |4.00 | 6.00
My problem is to get data from SQL to dynamically update chart.
Mysql data is like this:
id | age
1 | 12
2 | 21
3 | 31
4 | 11
5 | 31
And I want to echo like this:
[1,12] , [2,21] , [3,31] , [4,11] , [5,31]
I have tried this:
$sql = "SELECT id, age FROM tes";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$tes = $row['tes'];
$a = array($id,$tes);
echo json_encode($a, JSON_PRETTY_PRINT);
}
But it ended like this:
[1,12] [2,21] [3,31] [4,11] [5,31]
Collect all the rows into a 2-D array, then return that as JSON.
$a = array();
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$tes = $row['tes'];
$a[] = array($id,$tes);
}
echo json_encode($a, JSON_PRETTY_PRINT);
I've saved all my data to an array, and I want to get the 'name' of a supplied 'code'.
How to I get the array row of that code?
Also, is this the most efficient process?
id | code | name |
__________________________
1 | KNTY | Kentucky |
2 | PURD | Purdue |
3 | TEXS | Texas |
// Move data to array
$search = "SELECT * FROM table";
$query = mysqli_query($conn, $search);
while($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
}
// Code I want a name for
$code = "KNTY";
// MYSTERY STEP I NEED HELP WITH
$name = $array[$id]['name'];
I edit with the hint of the comment of itachi. You can use the code as the key of the $array:
$search = "SELECT * FROM table";
$query = mysqli_query($conn, $search);
$array = array();
while($row = mysqli_fetch_assoc($query)) {
$array[$row['code']] = $row['name'];
}
// Code I want a name for
$code = "KNTY";
$name = $array[$code];
Yes you could do something like that, while inside the fetch loop, assign the code as key. This must be unique though:
$search = 'SELECT * FROM table_name';
$query = mysqli_query($conn, $search);
while($row = mysqli_fetch_assoc($query)) {
// assign `$row['code']` as key to this rowset
$array[$row['code']] = $row;
}
$code = 'KNTY';
if(isset($array[$code])) { // add some checking, you wouldn't want undefined index errors
$name = $array[$code]['name'];
echo $name;
} else {
echo 'Sorry not found';
}
I have been trying to fureout how to create a dynamic multi dimensional array.
The reason for this is that I want to create a dropdown menu that will be created dynamically from the mysql
Sample database
|id|menu_name|menu_parent_id|
|1 |top menu1| 0 |
|2 |top menu2| 0 |
|3 |top menu3| 0 |
|4 |top menu4| 0 |
|5 |sub menu | 2 |
|6 |sub menu | 2 |
|7 |sub menu | 5 |
|8 |sub menu | 6 |
|9 |top menu | 0 |
I thought of starting from getting the menu with no parent then put it on an array
$parentIDs[0]=0;
$tempParentIDs = array();
$childIDs = array();
$menus = array();
$rows = 0;
$rows=0;
foreach($parentIDs AS $value){
$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$value");
while($temp = mysql_fetch_array($sql)){
//$tempParentIDs[] = $temp['service_id'];
//check if parent have child
$sql2 = mysql_query("SELECT * FROM service WHERE service_parent_id=$temp[service_id]") or die(mysql_error());
$rows = mysql_num_rows($sql2);
if($rows >= 1){
//This means there is a child
while($temp2 = mysql_fetch_array($sql2)){
$childIDs[] = $temp2['service_id'];
}
$tempParentIDs[$temp['service_id']] = $childIDs;
unset($childIDs);
} else {
//This means there is no child
}
}
}
echo "<pre>";
print_r($tempParentIDs);
echo "</pre>";
but after then I'm stuck.
I think you are looking for this:
$parentIDs[0]=0;
$tempParentIDs = array();
$childIDs = array();
$menus = array();
$rows = 0;
$multiDimensionalArray = NULL; //here I made change - vijay
$rows=0;
foreach($parentIDs AS $value){
$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$value");
while($temp = mysql_fetch_array($sql)){
$tempParentIDs = $temp['service_id']; //here I made change - vijay
//check if parent have child
$sql2 = mysql_query("SELECT * FROM service WHERE service_parent_id=$temp[service_id]") or die(mysql_error());
$rows = mysql_num_rows($sql2);
if($rows >= 1){
//This means there is a child
while($temp2 = mysql_fetch_array($sql2)){
$multiDimensionalArray[$tempParentIDs][] = $temp2['service_id']; //here I made change - vijay
}
// $tempParentIDs[$temp['service_id']] = $childIDs; //here I made change - vijay
// unset($childIDs); //here I made change - vijay
} else {
//This means there is no child
}
}
}
echo "<pre>";
print_r($multiDimensionalArray); //here I made change - vijay
echo "</pre>";
You should store array in php like this way :
This will maybe work for you
$next = 0;
$level = 0;
$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$next");
$temps = array();
while($temp = mysql_fetch_array($sql))
{
$temps[] = $temp;
}
foreach($temps as $temp)
{
echo $temp['service_id'];
}