JSON PHP Merge Same Inserted Data - php

I have this JSON which has the same ord_name , cust_id , Ord_num
{"orders":[{"id":"1","ord_name":"Nestea Bottle","ord_desc":"Nestea in a bottle","ord_price":"15","ord_qty":"2","customer_id":"54feec24bff73","ord_num":"13211554feec24bff73","price_x_quan":"30.00","image":"http://192.168.43.52/MMOS/uploads/nestea_bottled.jpg","subtotal":"","imgimg":"uploads/nestea_bottled.jpg"},{"id":"2","ord_name":"Nestea Bottle","ord_desc":"Nestea in a bottle","ord_price":"15","ord_qty":"4","customer_id":"54feec24bff73","ord_num":"13211554feec24bff73","price_x_quan":"60.00","image":"http://192.168.43.52/MMOS/uploads/nestea_bottled.jpg","subtotal":"","imgimg":"uploads/nestea_bottled.jpg"},{"id":"3","ord_name":"Nestea Bottle","ord_desc":"Nestea in a bottle","ord_price":"15","ord_qty":"1","customer_id":"54feec24bff73","ord_num":"13211554feec24bff73","price_x_quan":"15.00","image":"http://192.168.43.52/MMOS/uploads/nestea_bottled.jpg","subtotal":"","imgimg":"uploads/nestea_bottled.jpg"}],"o_total":[{"total":"105"}]}
my problem is , how to merge or just Overwrite programmatically the JSON with the 'same' ord_num , customer_id and ord_name
field that will update are qty = 7 , price_x_quan
What i want : Nestea in a bottle will have qty = 7 , price_x_quan = 105
this is my code for ordershow
<?php
mysql_connect('localhost','root','')or die ('No Connection');
mysql_select_db('dbmoms');
//$ord = $arr['ord_num']
$sum=0;
$total = $sum;
$sql1 ="SELECT * FROM orders ORDER BY id desc LIMIT 1";
if($row=mysql_fetch_array(mysql_query($sql1))){
$order_id=$row['ord_num'];
}
$sql ="SELECT * FROM orders WHERE ord_num = '$order_id' ";
$result = mysql_query($sql);
$arr["orders"] = array();
while($row = mysql_fetch_assoc($result)){
$arr['orders'][]= $row ;
$sum = $sum+$row['price_x_quan'];
}
$arr['o_total'][] = array('total' => "$sum" );
$json_encoded_string = json_encode($arr);
$json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
echo $json_encoded_string;
?>
please help !

Above:
$arr['orders'][]= $row ;
Put:
// Specify custom values for Nestea..
if( $row[ 'ord_desc' ] == 'Nestea in a bottle' )
{
$row[ 'ord_qty' ] = '7';
$row[ 'price_x_quan' ] = '105.00';
}

You can do this right in your MySQL query using SUM function with a GROUP BY clause.
As a side note you should consider using mysqli (where the trailing i stands for improved) or PDO for accessing your database, instead of the deprecated mysql interface. Now why on earth should I bother to do that?
$sql1 ="SELECT * FROM orders ORDER BY id desc LIMIT 1";
if($row=mysql_fetch_array(mysql_query($sql1))){
$order_id=$row['ord_num'];
}
// Use SUM and GROUP BY to let the database do the math, introducing
// the calculated 'sum_price_x_quan' and 'sum_ord_qty' columns
$sql = "
SELECT ord_num,
ord_desc,
sum(price_x_quan) as sum_price_x_quan,
sum(ord_qty) as sum_rod_qty
FROM orders
WHERE ord_num = '$order_id'
GROUP BY ord_num
";
$result = mysql_query($sql);
$arr = array();
if ($row = mysql_fetch_assoc($result)) {
$arr['orders'][] = $row ;
$arr['o_total'][] = array('total' => $row["sum_price_x_quan"]);
}
$json_encoded_string = json_encode($arr);
echo $json_encoded_string;
Output:
{
"orders": [
{
"ord_num": "13211554feec24bff73",
"ord_desc": "Nestea in a bottle",
"sum_price_x_quan": "105.00",
"sum_ord_qty": "7"
}
],
"o_total": [
{
"total": "105.00"
}
]
}

Related

Unable to get key value from a mysql multi-dimensional array

I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}

Flot with json and php

I made a json array with php. It works but it gives only the 'data' result from the first label and not the rest. Beside that it starts everytime with a number. How can i fix this?
$sql = $site->mysqli->query("SELECT id, title, event_start_date FROM events");
while($row = $sql->fetch_assoc()) {
$dataset[] = array('label' => $row['title']);
$sql2 = $site->mysqli->query("SELECT timestamp, event_id, COUNT(timestamp) AS row_count FROM order_products WHERE event_id = '".$row['id']."' GROUP BY DATE(FROM_UNIXTIME(timestamp))");
$count2 = $sql2->num_rows;
while($row2 = $sql2->fetch_assoc()) {
$dataset['data'][] = array(intval($row2['timestamp'] * 1000), (int)$row2['row_count']);
}
}
$results[]=$dataset;
die(Json_encode($results));
Result:
[{"0":{"label":"Label 1"},"data":[[1392894348000,10],
[1392998502000,3],[1393066962000,5],[1393262541000,3],
[1393577348000,5],[1393704543000,2],[1393780878000,1],
[1393882353000,3],"1":{"label":"Label 2"},"2":{"label":"Label 3"}}]
You should empty your $dataset for each event:
$sql = $site->mysqli->query("SELECT id, title, event_start_date FROM events");
while($row = $sql->fetch_assoc()) {
$dataset = array('label' => $row['title'], 'data' => array());
$sql2 = $site->mysqli->query("SELECT timestamp, event_id, COUNT(timestamp) AS row_count FROM order_products WHERE event_id = '".$row['id']."' GROUP BY DATE(FROM_UNIXTIME(timestamp))");
$count2 = $sql2->num_rows;
while($row2 = $sql2->fetch_assoc()) {
$dataset['data'][] = array(intval($row2['timestamp'] * 1000), (int)$row2['row_count']);
}
$results[]=$dataset;
}
die(json_encode($results));

PHP chart diagram to display skipped entry

I'm trying to create a graph like this http://jsfiddle.net/9mmrbjt7/1/
I have a script created that will add the data to the graph. The date and the value is stored in db and it works just fine.
The php script counts the number of dates and uses it as a value and assign it to the date.
The problem is if someone miss one day it skips the value which I understand.
So how can I assign value zero to skipped day?
2014-07-23
2014-07-23 = 2,
2014-07-24 -> wasn't submitted so the 0 should be added to the graph with the date.
2014-07-25
2014-07-25
2014-07-25= 3,
php script
$user_curr_id = $_SESSION['user_id'];
$sql = mysqli_query($con,"SELECT * FROM rosary WHERE user_ids = $user_curr_id ORDER BY datum ASC");
$array1 = array();
while($row = mysqli_fetch_array($sql)){
$array1[] = '"' . $row['datum'] . '"';
}
$tags = implode(', ', array_unique(array_map('trim',explode(',',implode(',',$array1)))));
$sql = mysqli_query($con,"SELECT datum, COUNT(datum) cnt
FROM rosary
WHERE user_ids = $user_curr_id
GROUP BY datum;");
$result = array();
while ($row = mysqli_fetch_array($sql)) {
$result[] = $row['cnt']; // add the content of field cnt
}
in js script
labels : ["Start",<?php echo $tags; ?>] -> list the dates from db
data : [0,<?php echo implode(',', $result); ?>]-> list values from db
php:
$sql = mysqli_query($con,"SELECT datum, COUNT(datum) as cnt
FROM rosary
GROUP BY datum
ORDER BY datum ASC;");
$result = array();
$start = null;
$end = null;
while ($row = mysqli_fetch_array($sql)) {
$result['"'.$row['datum'].'"'] = $row['cnt'];
if(is_null($start)) $start = $row['datum'];
$end = $row['datum'];
}
$res_array = array();
if(!is_null($start)){
$i = strtotime($start);
while($i <= strtotime($end)){
$res_array['"'.date('Y-m-d',$i).'"'] = 0;
$i = strtotime("+1 day",$i);
}
}
foreach($result as $date => $val){
$res_array[$date] = $val;
}
in js script
labels : ["Start",<?php echo implode(',',array_keys($res_array)) ?>],
data : [0,<?php echo implode(',', array_values($res_array)); ?>],

Putting results into an array in php

The code I have is the following
$sql = <<<SQL
SELECT p . * , s . *
FROM am_user p
INNER JOIN am_user_status s
USING ( user_id )
WHERE product_id =4
AND partner_logo = '1'
ORDER BY RAND( )
LIMIT 6
SQL;
$array = Array();
while ($row = mysql_fetch_array($result)) {
$array[] = $result;
}
echo $array;
However I am getting an error, I am just trying to get the results into an array. Does anyone know how I can achieve this?
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /var/sites/c/xxxxxxx/public_html/index.php on line 26
Thanks!
$sql = mysql_query("
SELECT p . * , s . *
FROM am_user p
INNER JOIN am_user_status s
USING ( user_id )
WHERE product_id =4
AND partner_logo = '1'
ORDER BY RAND( )
LIMIT 6";
$array = Array();
while ($row = mysql_fetch_array( $sql )) {
$array[] = $row;
}
echo "<pre>";
print_r( $array );
You have the sql statement, byt forgot to send it to mysql.
...
$result = mysql_query($SQL); // you forgot this
$array = Array();
while ($row = mysql_fetch_array($result)) {
$array[] = $result;
}
var_dump($array) ; // not echo $array

SyntaxError {stack: (...), message: "Unexpected token <"} tracker.js:41 parsererror

I want to retrieve the data from db using PHP
$device_owner_resultset=mysqli_query($con, "SELECT * FROM `device_owner_details` WHERE `deviceId` =$device_details_data_id");
$device_owner_resultset_data = mysqli_fetch_array($device_owner_resultset);
$owner_deviceid = $device_owner_resultset_data['deviceId'];
$owner_name = $device_owner_resultset_data['name'];
$name_fetch_rows = mysqli_fetch_row($device_owner_resultset);
$device_realtime_resultset=mysqli_query($con, "SELECT * FROM `device_realtime_stats` WHERE `deviceId` = $owner_deviceid LIMIT $start_from , $limit");
$rows_fetch = mysqli_fetch_row($device_realtime_resultset);
if(($total_pages<=$page) &&( $total_pages>0))
{
$device_details=array('devices'=> array());
for($i=1;$i<=20;$i++)
{
$details =array('name' => $name_fetch_rows[$i]-> name, 'latitude' => $rows_fetch[$i] -> currentLatitude, 'longitude' => $rows_fetch[$i] -> currentLongitude);
array_push($device_details['devices'],$details);
}
$response = json_encode($device_details);
echo $response;
}
Here i have an parse error, what is the mistake from my coding , i think error is in mysqli_fetch_rows and its calling array
You are not using mysqli_fetch_row($result) correctly. The function mysqli_fetch_row($result) does not return all the row data. It returns an array of a single row as an enumerated array. Try this code using this code instead:
// Now only selects name column and added LIMIT 1 to MySQL query for efficiency
$device_owner_resultset = mysqli_query($con, "SELECT name FROM `device_owner_details` WHERE `deviceId` = $device_details_data_id LIMIT 1");
// Now using mysqli_fetch_assoc($result)
// instead of mysqli_fetch_array($result) for clarity
$device_owner_resultset_data = mysqli_fetch_assoc($device_owner_resultset);
// Got rid of $owner_deviceid because it should be the same as $device_details_data_id
$owner_name = $device_owner_resultset_data['name'];
// Got rid of $name_fetch_rows because it is redundant with $device_owner_resultset_data
// Query now specifies which columns it selects for clarity and efficiency
$device_realtime_resultset = mysqli_query($con, "SELECT currentLatitude, currentLongitude FROM `device_realtime_stats` WHERE `deviceId` = $device_details_data_id LIMIT $start_from, $limit");
if ($total_pages <= $page && $total_pages > 0) {
$device_details=array('devices'=> array());
// This loops through all the rows from the query
while ($row = mysqli_fetch_assoc($device_realtime_resultset)) {
// $row is an associative array where the column name is
// mapped to the column value.
// The owner name should remain the same because there is
// only one owner.
$details = array('name' => $owner_name,
'latitude' => $row["currentLatitude"],
'longitude' => $row["currentLongitude"]
);
array_push($device_details['devices'], $details);
}
$response = json_encode($device_details);
echo $response;
}
If the columns of the device_realtime_stats table are not named currentLatitude and currentLongitude make sure they are renamed.
$mysql_all_resultset = mysqli_query($con, " SELECT dot.name, drs.currentLatitude, drs.currentLongitude FROM device_details dt, device_owner_details dot, device_realtime_stats drs WHERE dt.vendorId=$vendor_id AND dot.deviceId=dt.id AND drs.deviceId= dot.deviceId LIMIT $start_from, $limit ");
if(($total_pages<=$page) &&( $total_pages>0))
{
$device_details=array('devices'=> array());
while ($rows_fetch = mysqli_fetch_assoc($mysql_all_resultset))
{
$details =array('name' => $rows_fetch['name'], 'latitude' => $rows_fetch['currentLatitude'], 'longitude' => $rows_fetch['currentLongitude']);
array_push($device_details['devices'],$details);
}
$response = json_encode($device_details);
echo $response;
}

Categories