Outputting SQL query as line by line JSON - 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);

Related

Not able to pass array data

I am trying to create an array in $data, but it is not happening. I am using this code to make a day wise sale chart.
$data = array();
for ($i = 0; $i <= 10; $i++) {
$billdate = date('d-m-Y', strtotime("-$i day"));
$sqlQuery = "select sum(amount),bill_date from msr_bills WHERE bill_date='$billdate' ";
$result = mysqli_query($con, $sqlQuery);
$fetchamount = mysqli_fetch_row($result);
$sum = $fetchamount[0];
$data = new \stdClass();
$data->bill_date = $billdate;
$data->amount = $sum;
$report_JSON = json_encode($data);
echo $report_JSON.",";
}
You can merge your loop into one query, and then iterate over the results instead:
$data = array();
$billdate = date('Y-m-d', strtotime('-10 day'));
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE bill_date >= '$billdate'
GROUP BY bill_date";
$result = mysqli_query($sqlQuery);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = (object)$row;
}
$report_JSON = json_encode($data);
echo $report_JSON;
}
Note that your date format is not compatible with MySQL dates, which are stored in Y-m-d format, and I have changed that in the code. If your bill_date column is actually a text field stored in d-m-Y format, you will need to convert it in the query like so:
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE STR_TO_DATE(bill_date, '%d-%m-%Y') >= '$billdate'
GROUP BY bill_date";
Note also that you can in fact do the computation of $billdate internal to your SQL query using date arithmetic:
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE STR_TO_DATE(bill_date, '%d-%m-%Y') >= CURDATE() - INTERVAL 10 DAY
GROUP BY bill_date";
And if you are running MySQL 8.0+, you can do the entire operation in MySQL:
$sqlQuery = "SELECT JSON_ARRAYAGG(data) AS data
FROM (SELECT JSON_OBJECT('bill_date', bill_date, 'amount', SUM(amount)) AS data
FROM msr_bills
WHERE bill_date >= CURDATE() - INTERVAL 10 DAY
GROUP BY bill_date) d";
$result = mysqli_query($sqlQuery);
if ($result) {
$row = mysqli_fetch_assoc($result);
$report_JSON = $row['data'];
echo $report_JSON;
}
Demo on dbfiddle
Put your echo outside loop. remove code $report_JSON = json_encode($data);
$respnseArr = array();
{
.
.
.
$respnseArr[] = $data;
}
echo json_encode($respnseArr);

how to find the particular date data or next date data in mysql database?

I am trying to find the particular date data from database,
my concept is if 2018-11-30 is given to find in database if the date is present in database it should display the date in output, if not present it should add +1 date to 2018-11-30 and try to find the next date 2018-12-01 like wise it goes on.
but i am facing the problem the date is not checked in the database.i am not sure weather my code is correct or wrong can any one give me solution for it.
this is my code
$Firstdate = '2018-11-29';
$Lastdate = '2018-12-03';
$Sql2 = "SELECT ScheduleDate FROM `empdet`";
$result2 = mysqli_query($con, $Sql2);
while($row = mysqli_fetch_array($result2))
{
if($row["ScheduleDate"]==$Firstdate)
{
$DBfirstdate==$Firstdate;
echo "$DBfirstdatebb",$DBfirstdate;
break;
}
else {
$checkFDBdate=date('Y-m-d', strtotime("+1 day", strtotime($Firstdate)));
if($row["ScheduleDate"]==$checkFDBdate)
{
$DBfirstdate=$checkFDBdate;
echo "$DBfirstdate",$DBfirstdate;
break;
}
}
}
$Sql3 = "SELECT ScheduleDate FROM `empdet`";
$result3 = mysqli_query($con, $Sql3);
while($row = mysqli_fetch_array($result3))
{
if($row["ScheduleDate"] == $Lastdate) {
$DBlastdate==$Lastdate;
echo "$DBlastdateBB",$DBlastdate;
break;
}
else {
$checkLDBdate=date('Y-m-d', strtotime("-1 day", strtotime($Lastdate)));
if($row["ScheduleDate"]==$checkLDBdate)
{
$DBlastdate=$checkLDBdate;
echo "$DBlastdate",$DBlastdate;
break;
}
}
}
$sql ="select * from empdet where ScheduleDate between '".$DBfirstdate."' and '".$DBlastdate."'";
$result = $con->query($sql);
SELECT ScheduleDate FROM `empdet` where ScheduleDate > '$Firstdate' and ScheduleDate < '$Lastdate' order by ScheduleDate limit 1
Try this way. You will get the first raw from the date range given.
Select stuff from somewhere where something > 'value' order by something limit 1

creating outer array php

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);

SQL Server query returning no results in PHP, but runs fine in Management Studio

I have a rather large query that works fine in Microsoft SQL Server Management Studio. However when I try to run the same query in PHP, I'm getting no results. Here is my code, I know this is the worst way to connect to the database.
Public function GetClockedHours() {
$conn = odbc_connect('easydo', '', '');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql = "WITH ByDays AS ( -- Number the entry register in each day
SELECT
EventTm AS T,
CONVERT(VARCHAR(10),EventTm,102) AS Day,
FLOOR(CONVERT(FLOAT,EventTm)) DayNumber,
ROW_NUMBER() OVER(PARTITION BY FLOOR(CONVERT(FLOAT,EventTm)) ORDER BY EventTm) InDay
FROM CHINA_VISION_DorEvents
Where DorCtrls_Ref = '16' AND CardCode = '000006f1' AND CONVERT(Date,EventTm) > dateadd(day, -7, getdate())
)
,Diffs AS (
SELECT
E.Day,
E.T ET, O.T OT, O.T-E.T Diff,
DATEDIFF(S,E.T,O.T) DiffSeconds -- difference in seconds
FROM
(SELECT BE.T, BE.Day, BE.InDay
FROM ByDays BE
WHERE BE.InDay % 2 = 1) E -- Even rows
INNER JOIN
(SELECT BO.T, BO.Day, BO.InDay
FROM ByDays BO
WHERE BO.InDay % 2 = 0) O -- Odd rows
ON E.InDay + 1 = O.InDay -- Join rows (1,2), (3,4) and so on
AND E.Day = O.Day -- in the same day
)
SELECT Day,
SUM(DiffSeconds) Seconds,
CONVERT(VARCHAR(8),
(DATEADD(S, SUM(DiffSeconds), '1900-01-01T00:00:00')),
108) TotalHHMMSS -- The same, formatted as HH:MM:SS
FROM Diffs GROUP BY Day
ORDER BY Day desc";
$rs = odbc_exec($conn, $sql);
if (!$rs) {
exit("Error in SQL");
}
$array = array();
$i = 1;
while ($row = odbc_fetch_array($rs, $i)) {
foreach ($row AS $key => $value) {
$array[$i][$key] = $row[$key];
}
$i++;
}
var_dump($array);
return $array;
}
The expected result would be an array of results and the results would be:
Date Seconds hours
2015.01.27 18055 05:00:55
2015.01.26 33491 09:18:11
2015.01.23 32649 09:04:09
2015.01.22 31554 08:45:54
2015.01.21 31889 08:51:29
However what were are getting is an array of nothing.
How many results sets do you get back? If it's more than 1 then you need to pick the correct resultset:
bool odbc_next_result ( resource $result_id )
http://php.net/manual/en/function.odbc-next-result.php
I had this same problem. In my case I was executing like this
$sql = "SELECT * FROM table1";
$resultSet = odbc_exec($sqllink, $sql);
while ($data = odbc_fetch_array($resultSet)) {
$sql = "SELECT * FROM table2";
$resultSet2 = odbc_exec($sqllink, $sql);//failed here
while ($data2 = odbc_fetch_array($resultSet2)) {
//something here
}
}
and I changed like this and it worked
$sql = "SELECT * FROM table1";
$resultSet = odbc_exec($sqllink, $sql);
// Create an array and store the results
$queryResult = array();
while ($data = odbc_fetch_array($resultSet)) {
// push the required content into the array
$queryResult[$data['id']]['name'] = $data[name];
}
foreach($queryResult as $row) {
$sql = "SELECT * FROM table2";
$resultSet2 = odbc_exec($sqllink, $sql);
while ($data2 = odbc_fetch_array($resultSet2)) {
// something here
}
}

SELECT COUNT with date and type

i have this function :
function get_user_dep($userid)
{
$sql = mysql_query("SELECT COUNT(userid) AS total_dep FROM `userdep` WHERE `type` LIKE 'Depozitare' AND DATE(`date`) <= NOW() AND DATE(`date`) >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
$row = mysql_fetch_array($sql);
$count = $row['total_dep'];
if ($count > 1) {
return 'Yes';
} else {
return 'No';
}
}
with database userdep
id/userid/type/date/amouth
i made with assoc, numrow , and it returns me No , and in the database i have more than 4 entrys in interval 7 days.
Sorry for having to ask this in an answer - my rep is too low. What field type is your date column? From what I just read in your comments on the answer below, the DATE field requires 'yyyy-mm-dd'.
1) SQL is valid.
2) Change this:
$row = mysql_fetch_array($sql);
to this:
$row = mysql_fetch_array($sql, MYSQL_ASSOC);
or to this:
$row = mysql_fetch_assoc($sql);
3) Also you can try this to check what you received back from DB.
echo print_r($row, true);

Categories