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;
}
Related
UPDATE: a solution has been found stated below: however new issue poses i didnt want to keep creating question so updated this one when i use ajax to pass through to html i get the following error response.forEach is not a function
where the code is as below is this because there are now 2 arrays?
$.get('php/test.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
});
});
Im Pretty naff when it comes to this type of thing but i need to try get these 2 queries added to 1 ajax I have been told i should add both queries to an outer array but im not sure how to do this and the example i got was $array = $other_array
but im not sure how to write it any help would be greatly appreaciated
$sql = "SELECT beacon,TIME_FORMAT(TIMEDIFF(max(`time`),min(`time`)), '%i.%s')
AS `delivery_avg`
FROM `test`.`test`
where date = CURDATE()
and time > now() - INTERVAL 30 MINUTE
group by beacon ";
$result = $conn->query($sql);
$sql2 = 'SELECT
*
FROM
(SELECT
beacon,location,date,
COUNT(location) AS counter
FROM `test`.`test`
WHERE `date` = CURDATE() and `time` > NOW() - interval 40 second
GROUP BY beacon) AS SubQueryTable
ORDER BY SubQueryTable.counter DESC;';
$result = $conn->query($sql2);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$result2 = mysqli_query($conn , $sql2);
$rows2 = array();
while($r = mysqli_fetch_assoc($result2)) {
$rows2[] = $r;
}
echo json_encode($rows2);
You already got most of it right. To get the data in one go, you can combine the arrays (see the line staring with $result) and then send it JSON formatted.
$sql1 = "SELECT ...";
// Query the database
$result1 = $conn->query($sql);
// Fetch the result
$rows1 = $result1->fetch_all(MYSQLI_ASSOC);
// Same for second query
$sql2 = 'SELECT ...';
$result2 = $conn->query($sql2);
$rows2 = $result2->fetch_all(MYSQLI_ASSOC);
$result = array(
'query1' => $rows1,
'query2' => $rows2
);
header("Content-Type: application/json");
echo json_encode($result);
Some more hints:
You only need to run the query once (you have ->query() and mysqli_query() in your code).
You don't need the loop to get all result rows. The function mysqli_fetch_all() does that for you.
When you have your 2 arrays with db results, you can do something like this :
$return = array (
$result,
$result2
);
echo json_encode($return);
$sendResponse = array (
'sql1' => $sqlResult1,
'sql2' => $sqlResult2
);
echo json_encode($sendResponse);
This would be a more suitable and convenient (from JavaScript size) way
$response = [];
$response['result_first_query'] = $rows;
$response['result_second_query'] = $rows2;
echo json_encode($response);
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"
}
]
}
The code below returns nothing, but if I remove this line:
'desc' => $row['DESC'],
from the function it works fine.
DESC Is a valid column in the database and when I run the full query in phpmyadmin, it returns the desired result.
I am not sure why this line
'desc' => $row['DESC'],
breaks the return of the result.
=======
After more investigating I can see the JSON output has the same issue.
Altering the column name (since DESC is a keyword) and reflecting the changes in the query has no effect.
========
function get_all_subjects($db1) {
$stmt = $db1->query("SELECT DISTINCT NAME, DESC, CLASSCODE FROM tbl_subjects WHERE VISIBLE = 1 ORDER BY NAME ASC");
$stmt->execute();
$count = $stmt->rowCount();
$column = array();
if ($count >0)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$column[] = array(
'name' => $row['NAME'],
'desc' => $row['DESC'],
'cc' => $row['CLASSCODE']
);
}
return json_encode(array('subjects' =>$column));
}
else
{
return $count;
}
}
DESC is a reserved word in SQL. If you want to use it as a column, you should protect it with forward quotes:
function get_all_subjects($db1) {
$stmt = $db1->query("SELECT DISTINCT NAME, `DESC` AS D, CLASSCODE FROM tbl_subjects WHERE VISIBLE = 1 ORDER BY NAME ASC");
$stmt->execute();
$count = $stmt->rowCount();
$column = array();
if ($count >0)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$column[] = array(
'name' => $row['NAME'],
'desc' => $row['D'], // Using the alias, just in case
'cc' => $row['CLASSCODE']
);
}
return json_encode(array('subjects' =>$column));
}
else
{
return $count;
}
}
DESC is a reserved Keyword do something like
SELECT DISTINCT NAME, DESC as yourVar, CLASSCODE FROM tbl_subjects WHERE VISIBLE = 1 ORDER BY NAME ASC
and then like that
'desc' => $row['yourVar'],
$stmt = $db1->query("SELECT DISTINCT `NAME`, `DESC`, `CLASSCODE` FROM `tbl_subjects` WHERE `VISIBLE` = 1 ORDER BY `NAME` ASC");
there was syntax error because desc is reserved keyword, you have to use quotes, the best habbit is quote each column and each table name
Thank you all for your answers - I found the problem and what broke the script was that my strings in my JSON values had several - in them.
It took me a while to find it :-)
I am trying to get some data from my sql. But the result for the $arra_detail[] keeps repeating ... here is my code .. please review it and let me know of the mistake I am making .. any help will be appreciated ..
//Process of getting data from table
$sql = "SELECT * FROM projects JOIN project_details ON projects.project_id=project_details.project_id";
$results = $conn->query($sql);
if($results->num_rows > 0){
while($row = $results->fetch_assoc()){
$pid = $row["project_id"];
$detailQuery = "SELECT * FROM project_details WHERE project_id = $pid";
$details = $conn->query($detailQuery);
if($details->num_rows > 0){
while ($r = $details->fetch_assoc()){
$projectDetails[] = array(
"project_detail" => $r["project_detail"],
"project_payment" => $r["project_payment"],
"project_payment_date" => $r["project_payment_date"],
"project_payment_status" => $r["project_payment_status"]
);
}
}
$data[$row["project_name"]] = array(
"project_id" => $row["project_id"],
"project_start_date" => $row["project_start_date"],
"project_due_date" => $row["project_due_date"],
"project_currency" => $row["project_currency"],
"poject_details" => $projectDetails
);
}
echo "<pre>", print_r($data) , "</pre>";
} else{
echo "No data found ";
}
use inner join query instead of two query with 2 loop
SELECT * FROM projects,project_details WHERE
projects.project_id=project_details .project_id
I have this function:
function findAllmessageSender(){
$all_from = mysql_query("SELECT DISTINCT `from_id` FROM chat");
$names = array();
while ($row = mysql_fetch_array($all_from)) {
$names[] = $row[0];
}
return($names);
}
that returns all the ID of my users in a private messaging system. Then I want to get the all the messages where the user_id is equal to the user logged in and from_id is equal to all from_id I got from the previous function:
function fetchAllMessages($user_id){
$from_id = array();
$from_id = findAllmessageSender();
$data = '\'' . implode('\', \'', $from_id) . '\'';
//if I echo out $ data I get these numbers '113', '141', '109', '111' and that's what I want
$q=array();
$q = mysql_query("SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id` IN($data)") or die(mysql_error());
$try = mysql_fetch_assoc($q);
print_r($try);
}
print_r return only 1 result:
Array (
[id] => 3505
[from_id] => 111
[to_id] => 109
[message] => how are you?
[sent] => 1343109753
[recd] => 1
[system_message] => no
)
But there should be 4 messages.
You have to call mysql_fetch_assoc() for each row that is returned. If you just call mysql_fetch_assoc() once then its only going to return the first row.
Try something like this:
$result = mysql_query("SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id` IN($data)") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
'mysql_fetch_assoc' returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
You need to iterate array like:
while ($row = mysql_fetch_assoc($q)) {
echo $row["message"];
}