Php sum data between interval date - php

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;

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

Outputting SQL query as line by line JSON

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

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)); ?>],

Adding 2 days and comparing

I've written some code to check if 2 days have passed using 2 dates, but it does not seem to work.
<?php
date_default_timezone_set('Europe/Amsterdam');
$_connection = mysqli_connect("localhost", "root", "root", "theater") or die("Error: " . mysqli_error());
$query = "SELECT * FROM Reservering";
$result = mysqli_query($_connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$res = strtotime($row['ReserveringsDatum']);
echo date('d-m-y', $res);
}
mysqli_close($_connection);
?>
$row['ReserveringsDatum'] is a date which looks like this: "07-01-14" (example).
For some reason the echo date('d-m-y', $res); shows me "14-01-07", which is just the day and year being reversed.
Edit:
For those wondering how it ended up, here is the working code:
<?php
date_default_timezone_set('Europe/Amsterdam');
$_connection = mysqli_connect("localhost", "root", "root", "theater") or die("Error: " . mysqli_error());
$query = "SELECT *, DATEDIFF(NOW(), DATE(ReserveringsDatum)) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2 ";
$result = mysqli_query($_connection, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['Betaalt'] == 'nee') {
$query2 = "DELETE FROM Reservering WHERE `ReserveringID` = '".$row['ReserveringID']."'";
mysqli_query($_connection, $query2);
}
}
mysqli_close($_connection);
?>
As said in the comment, i would make the selection within SQL. There is not need selecting all the rows and filter them in PHP. Its something better done in SQL.
Simple Example:
SELECT *, DATEDIFF(NOW(), ReserveringsDatum) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2
Make sure reserveringsdatum is a DATE, if its a TIMESTAMP you need to convert it to DATE.
SELECT *, DATEDIFF(NOW(), DATE(ReserveringsDatum)) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2
Try this
$res = strtotime($row['ReserveringsID']);
$limit = strtotime($row['ReserveringsID']) + strtotime("+2 day", $res);
var_dump($res); var_dump($limit);
if($limit > $res) {
echo "2 days have passed";
} else {
echo "2 days have not yet passed";
}
I think you need to fix you're condition.
If you want to check if $res is more than two days you have to compare limit to the current time, instead of $res.
$res = strtotime($row['ReserveringsID']);
$limit = strtotime('+2 days', $res);
if($limit < time()) {
echo "2 days have passed";
} else {
echo "2 days have not yet passed";
}
Your problem is in this line
$limit = strtotime($row['ReserveringsID']) + $2days;
You need to add 2 days like this one
$res = strtotime($row['ReserveringsID']);
$limit = strtotime('+2 days', $res);
Working demo of adding 2 days to a date
https://eval.in/86632
How do I add 24 hours to a unix timestamp in php?
Adding days to a timestamp

Categories