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);
Related
I have a working code that filters data from the date range.
MY WORKING CODE
<?php
//connection
$conn = new mysqli('xxxx', 'xxxx','xxxx', 'xxxx');
$start = date('Y-m-d', strtotime($_POST['date_start']));
$end = date('Y-m-d', strtotime($_POST['date_end']));
$output = array('error' => false, 'data' => '');
$sql = "SELECT * FROM users WHERE cosafai='polizza' and datapratica BETWEEN '$start' AND '$end'";
$query = $conn->query($sql);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$output['data'] .= "
<tr>
<td>".$row['name']."</td>
<td>".$row['cognome']."</td>
<td>".$row['targa']."</td>
<td>".$row['compagniascelta']."</td>
<td>".$row['premiopolizza']."</td>
<td>".date('M d, Y', strtotime($row['datapratica']))."</td>
</tr>
";
}
}
else{
$output['error'] = true;
}
echo json_encode($output);
?>
now I need to sum a specific column ( Premio polizza )during the dates interval
thinking something like
$sql = "SELECT SUM(premiopolizza) as sum FROM users WHERE cosafai='polizza' and datapratica BETWEEN '$start' AND '$end'";
but honestly, I can't manage it ;)
my final result should be
final result
Since you 're looping over the database result anyway, you can sum up in your while loop.
$sum = 0;
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$sum += $row['premiopolizza'];
$output['data'] .= "
...
";
}
}
The variable $sum is the addition of all $row['premiopolizza'] at the end. There is no need for an additional sql statement in my eyes. At the end you can use the sum in your output like ...
$output['sum_premiopolizza'] = $sum;
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);
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)); ?>],
I have a table in mysql which has a startdate and enddate.
An example of 1 row would be:
startdate -> 20121224
endate -> 20121226
title -> name
this would return (OUTPUT!!!):
[{"user":"378","date":"UNIX_TIMESTAMP(startdate)","title":"name","description":"6 Days","url":"UNIX_TIMESTAMP(enddate)","bmanager":"manager name","academic_year":"20120801","division":"division name","manager_id":"3"}]
As this record spans over 3 days i would like the JSON to output one for each date (the only differnce being the date, please see below) I WANT THIS INSTEAD
[{"user":"378","date":"UNIX_TIMESTAMP(1st date)","title":"name","description":"6 Days","url":"UNIX_TIMESTAMP(1st date)","bmanager":"manager name","academic_year":"20120801","division":"division name","manager_id":"3"},
{"user":"378","date":"UNIX_TIMESTAMP(2nd date)","title":"name","description":"6 Days","url":"UNIX_TIMESTAMP(2nd date)","bmanager":"manager name","academic_year":"20120801","division":"division name","manager_id":"3"},
{"user":"378","date":"UNIX_TIMESTAMP(3rd date)","title":"name","description":"6 Days","url":"UNIX_TIMESTAMP(3rd date)","bmanager":"manager name","academic_year":"20120801","division":"division name","manager_id":"3"},]
THIS IS THE SCRIPT IM USING:
$sqldata = mysql_query('
SELECT
datediff(requests.end_date, requests.start_date) as numdays,
requests.user,
UNIX_TIMESTAMP(requests.start_date) AS date,
requests.employee AS title,
requests.days AS description,
UNIX_TIMESTAMP(requests.end_date) AS url,
business.line_manager AS bmanager,
requests.academic_year,
business.academic_year,
business.division,
line_managers.userid AS manager_id
FROM requests
INNER JOIN holiday_entitlement_business_manual AS business ON requests.user=business.userid AND requests.academic_year=business.academic_year
INNER JOIN line_managers ON business.line_manager=line_managers.name
WHERE requests.approved = 1
');
$posts = array();
while($row = mysql_fetch_assoc($sqldata))
{
$row['date'] = $row['date'].'000';
$row['url'] = $row['url'].'000';
$posts[] = $row;
}
mysql_free_result($sqldata);
die(json_encode($posts));
Try to replace your code by the following:
$sqldata = mysql_query('
SELECT
requests.start_date as startdate,
datediff(requests.end_date, requests.start_date) as numdays,
requests.user,
UNIX_TIMESTAMP(requests.start_date) AS date,
requests.employee AS title,
requests.days AS description,
UNIX_TIMESTAMP(requests.end_date) AS url,
business.line_manager AS bmanager,
requests.academic_year,
business.academic_year,
business.division,
line_managers.userid AS manager_id
FROM requests
INNER JOIN holiday_entitlement_business_manual AS business ON requests.user=business.userid AND requests.academic_year=business.academic_year
INNER JOIN line_managers ON business.line_manager=line_managers.name
WHERE requests.approved = 1
');
$posts = array();
while($row = mysql_fetch_assoc($sqldata))
{
$startDate = $row['startdate'];
unset($array['startdate']);
$dayDiff = $row['numdays'];
$row['date'] = $row['date'].'000';
$row['url'] = $row['url'].'000';
for($i = 0; $i <= $dayDiff; $i++)
{
$row['date'] = ...; // Do here the date parsing and add $i to the days
$posts[] = $row;
}
}
mysql_free_result($sqldata);
die(json_encode($posts));
These functions dateparse() and mktime() will probably help you with the date manipulation.
Not sure whether I got your point. This could give you a starting point.
Basically, you need to fetch all rows, and then create one record for every day you wish to take into account.
$sqldata = mysql_query('
SELECT
datediff(requests.end_date, requests.start_date) as numdays,
requests.user,
UNIX_TIMESTAMP(requests.start_date) AS date,
requests.employee AS title,
requests.days AS description,
UNIX_TIMESTAMP(requests.end_date) AS url,
business.line_manager AS bmanager,
requests.academic_year,
business.academic_year,
business.division,
line_managers.userid AS manager_id
FROM requests
INNER JOIN holiday_entitlement_business_manual AS business ON requests.user=business.userid AND requests.academic_year=business.academic_year
INNER JOIN line_managers ON business.line_manager=line_managers.name
WHERE requests.approved = 1
');
$posts = array();
while($row = mysql_fetch_assoc($sqldata))
{
$row['date'] = $row['date'];
$row['url'] = $row['url'];
for($x = $row['date']; $x < $row['url']; $x+= 86400) {
// where 86400 makes you advancing by a day in secs
$row['date'] = $x;
$row['url'] = $x;
$posts[] = $row;
}
$posts[] = $row;
}
mysql_free_result($sqldata);
die(json_encode($posts));
Everything here is working except the UPDATE command... The INSERT works fine but alas, I'm stuck.
$queryLastDateArray = "SELECT date FROM schedule ORDER BY ID DESC LIMIT 1";
$lastDateArray = mysql_query($queryLastDateArray);
while($row = mysql_fetch_array($lastDateArray))
{
$lastDate = $row['date'];
}
$lastDatePlusOne = date("Y-m-d", strtotime("+1 day", strtotime($lastDate)));
$newDatesArray = GetDays($lastDatePlusOne, $_POST[date]);
$i = 0;
while($i < count($newDatesArray))
{
if ((date('D', strtotime($newDatesArray[$i]))) == 'Fri')
{
$insDate = "INSERT INTO schedule (date) VALUES ('$newDatesArray[$i]')";
$result = mysql_query($insDate);
$insEmp = "UPDATE schedule SET schedule.jakes = schedule_default.jakes FROM schedule, schedule_default WHERE schedule.date = '$newDatesArray[$i]' AND schedule_default.ID = '5'";
$result2 = mysql_query($insEmp);
}
$i++;
}
Try writing the update like this:
"UPDATE schedule SET schedule.jakes = (SELECT schedule_default.jakes FROM schedule_default WHERE schedule.date = '$newDatesArray[$i]' AND schedule_default.ID = '5')";
Multiple table UPDATE syntax is:
UPDATE schedule, schedule_default
SET schedule.jakes = schedule_default.jakes
WHERE schedule.date = '$newDatesArray[$i]'
AND schedule_default.ID = '5'