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);
Related
$frame_type = '';
$ret = mysqli_query($con, "select * from products where status='1' AND frame_type = '$frame_type' ");
while ($row = mysqli_fetch_array($ret)) {
$emparray[] = $row;
}
Get All Rows If The $frame_type Is Empty I am trying this way but i get zero rows , How to fix that Where $frame_type has value then send to query else not
There are a some of things that is wrong with your question (code). But if you only want answer. Just copy this
$frame_type = '';
$query = "select * from products where status='1' ";
// strlen has value
if(strlen($frame_type)) {
$query .= "AND frame_type = '$frame_type'";
}
$ret = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($ret)) {
$emparray[] = $row;
}
PS: It's never a safe idea to pass everything to the query. Use prepared statement if you can.
I am running a line graph on RGraph framework, and I am using a SELECT COUNT statement for rejected, accepted, approved etc.....counting how many items was rejected or accepted etc and then dumping the query data into an array, However I am looking for an easier way to implement this query, instead of running a query on each unique row value, also thinking in the way if I have to encounter other column data besides rejected, accepted or etc....I wouldnt, my code doesnt seem very scalable then. Please help
So far, I am running a query for each keyword, hope my code explains this.
The final variable is what i am feeding to RGRAPH, This works fine as it is, however it isn't the right way, and not very scalable, should my row data change.
<?php
$cxn = mysqli_connect("localhost","root","", "csvimport");
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = 'rejected'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$rejected = $display[0];
//echo $rejected;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion =
'accepted'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$accepted = $display[0];
//echo $accepted;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = '-'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$dash = $display[0];
//echo $dash;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion =
'approved'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$approved = $display[0];
//echo $approved;
$datarray = [$rejected, $accepted, $dash, $approved];
print_r($datarray);
$data_string = "[" . join(", ", $datarray) . "]";
echo "<br>";
print_r($data_string);
?>
You can just use GROUP BY and add the conclusion column to the result set, so
SELECT conclusion, COUNT(*) as total
FROM table_1
WHERE conclusion in ('rejected', 'accepted', '-', 'approved')
GROUP BY conclusion
Then retrieve each row of the result set
$totals = [];
while($row = mysqli_fetch_array($result)) {
$totals [$row[0]] = [$row[1]];
}
and $totals will be an array something like
array( 'accepted' => 12,
'approved' => 20...)
If you want all of the conclusions, then just remove the WHERE conclusion in line and it will return all of the possibilities along with the count.
I am creating a time attendance PHP script. I started from storing data in the database MySQL and use different tables for the Punch-in/Punch-out, Breaks, Lunch/Dinner breaks.
Each one of the casualties mentioned before have a table which is structured with an:
ID, start, end, flag
I have already tried to do this with the following code of foreach but unsuccessfully!
foreach ($total as $key => $row) {
$start[$key] = $row['start'];
}
$final = array_multisort($start, SORT_DESC, $total);
echo $final;
Here is the code that I have made with 2 SELECT MySQL queries
$result = mysqli_query($db, "SELECT * FROM time WHERE username =
'$user_check' ORDER BY start DESC");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
} $db->next_result();
$result = mysqli_query($db, "SELECT * FROM break WHERE username =
'$user_check' ORDER BY start DESC");
$data2 = array();
while ($row = mysqli_fetch_assoc($result)) {
$data2[] = $row;
}
$total = array_merge ($data, $data2);
I would like to have 1 array of this 2 queries sorted DESC by start as I will use this array to populate a table in DESC order.
Use UNION ALL in your query, instead of merge arrays. Let the database do the work for you:
SELECT * FROM
(SELECT * FROM time WHERE username = '$user_check'
UNION ALL
SELECT * FROM break WHERE username = '$user_check'
) ORDER BY start DESC
PS: Your code is vulnerable to SQL Injection. You should use prepared statement instead.
Im trying to merge or put an Array (called '$rows_ban') inside a sub item of another array (called '$rows') in a final array named '$rows_final'.
Im using array_merge but returns null inside 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[null]}
It should return the results in of the second query inside the 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[{...},{...},{...}]}
PHP Script:
$rows = array();
$rows_ban = array();
$rows_final= array();
$result1 = mysqli_query($link,"SELECT `id`,`sync_date`,`sync_time` FROM sync_log");
while($r = mysqli_fetch_array($result1)) {
$rows['date']= $r[2];
$rows['hour']= $r[3];
$rows['data'][]= null;
}
$result2 = mysqli_query($link,"SELECT cod, name, total from totals " );
while($r = mysqli_fetch_array($result2)) {
$rows_ban['cod'] = $r[0];
$rows_ban['name'] = $r[1];
$rows_ban['total'] = $r[2];
$result3 = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod=".$r[0]." order by dates desc");
while($r = mysqli_fetch_assoc($result3)) {
$rows_ban['sub_data'][] = $r;
}
$rows_final = array_merge($rows['data'],$rows_ban);
// here im trying to merge the $rows_ban array inside the
$rows['data']
}
echo json_encode($rows_final);
Not sure if that's what you wanted to accomplish since your description is very poor and hard to understand.
$output = [];
$tmpRows = [];
$result = mysqli_query($link, 'SELECT `id`,`sync_date`,`sync_time` FROM sync_log');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$output['date'] = $tmp[0]['sync_date'];
$output['time'] = $tmp[0]['sync_time'];
}
$result = mysqli_query($link, 'SELECT cod, name, total from totals ');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['cod'] = $tmp[0]['cod'];
$tmpRows['name'] = $tmp[0]['name'];
$tmpRows['total'] = $tmp[0]['total'];
$result = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod={$tmp[0]['cod']} order by dates desc");
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['sub_data'] = $tmp[0];
}
$output['data'] = $tmpRows;
}
print_r(json_encode($output));
Also array_merge doesn't work like you think it does. It returns merged array like it's name states. Regarding to your code, final result would be exactly $rows_ban encoded to json.
http://php.net/manual/en/function.array-merge.php
My SQL query is selecting date and doing a count, as well as grouping by date.
I don't know how to output line by line JSON output.
$sql = "SELECT DATE(timestamp), COUNT(eventid)
FROM `tablex`
WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
GROUP BY DATE(timestamp) ";
$stream = mysqli_query($conn, $sql);
if (mysqli_num_rows($stream) > 0) {
while($row = mysqli_fetch_assoc($stream)) {
// Is this where I should echo JSON?
// The problem is I'm not retrieving records but count and doing
// a grouping
}}
Use mysqli_fetch_array(), also take the count with mysql_num_rows():
$sql = "SELECT DATE(timestamp), COUNT(eventid)
FROM `tablex`
WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
GROUP BY DATE(timestamp) ";
$stream = mysqli_query($conn, $sql);
if (mysqli_num_rows($stream) > 0) {
$rowCount = mysql_num_rows($result);
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
// Process JSON here use $row[0], $row[1], and so
}
}
Whatever you like to return as a JSON-string, you should always write your data into a single array, then use this nice little PHP-function called json_encode(). For example:
$sql = "SELECT
DATE(timestamp) as date_timestamp,
COUNT(eventid) as count_eventid
FROM `tablex`
WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
GROUP BY DATE(timestamp);";
$stream = mysqli_query($conn, $sql);
// prepare return array
$mydata = array(
'eventcount' => 0
);
if (mysqli_num_rows($stream) > 0) {
while($row = mysqli_fetch_assoc($stream)) {
// just collect your data here, do not JSONify here
$mydata['eventcount'] += $row['count_eventid'];
}
}
// We got all our data, so return JSON encoded array
echo json_encode($mydata);
You will get something like
{"eventcount":"1234"}
I managed to get an output:
$stream = mysqli_query($conn, $sql);
$lines = array();
while($line = mysqli_fetch_assoc($stream)) {
$llines[] = $line;
}
print json_encode($lines);