retrieve data based on date range using mysql ,php - php

I am working on WPF where I have two datepickers when I try to retrieve the information on date range it displays only one record on all dates(same record displaying multiple times eg : date chosen from 01/10/2013 - 3/10/2013) where I have 3 different records on each day but my output is the first record displayed 3 times with same date and time.
function cpWhitelistStats() {
$startDate = $_POST['startDate'];
$startDateTime = "$startDate 00:00:00";
$endDate = $_POST['endDate'];
$endDateTime = "$endDate 23:59:59";
$cpId = $_POST['id'];
$cpName = etCommonCpNameById($cpId);
print "<h2 style=\"text-align: center;\">Permitted Vehicle Summary</h2>";
print "<h2 style=\"text-align: center;\">for $cpName</h2>";
$tmpDate = explode("/", $startDate);
$startYear = $tmpDate[2];
$startMonth= $tmpDate[1];
$startDay = $tmpDate[0];
$tmpDate = explode("/", $endDate);
$endYear = $tmpDate[2];
$endMonth= $tmpDate[1];
$endDay = $tmpDate[0];
$startDateTime = "$startYear-$startMonth-$startDay 00:00:00";
$endDateTime = "$endYear-$endMonth-$endDay 23:59:59";
$custId = $_SESSION['customerID'];
$realCustomerId = $_SESSION['realCustomerId'];
$maxVal = 0;
if ($custId != "") {
$conn = &newEtConn($custId);
// Get the whitelist plates
$staticWhitelistArray = etCommonMkWhitelist($conn, $cpId);
array_shift($staticWhitelistArray);
$startLoopDate = strtotime($startDateTime);
$endLoopDate = strtotime($endDateTime);
$oneDay = 60 * 60 * 24;
// Get the entries
$plateList = array_keys($staticWhitelistArray);
$plate_lookup = implode('","', $plateList);
$sql = "SELECT plate, entry_datetime, exit_datetime FROM stats WHERE plate IN (\"$plate_lookup\") AND entry_datetime > \"$startDateTime\" AND entry_datetime < \"$endDateTime\" AND carpark_id=\"$cpId\" ";
$result = $conn->Execute($sql);
if (!$result) {
print $conn->ErrorMsg();
exit;
}
$rows = $result->fields;
if ($rows != "") {
unset($myArray);
foreach($result as $values) {
$plate = $values['plate'];
$new_platelist[] = $plate;
$inDateTime = $values['entry_datetime'];
$outDateTime = $values['exit_datetime'];
$tmp = explode(' ', $inDateTime);
$inDate = $tmp[0];
$in_ts = strtotime($inDateTime);
$out_ts = strtotime($outDateTime);
$duration = $out_ts - $in_ts;
$dur_array = intToDateArray($duration);
$dur_string = '';
if ($dur_array['days'] > 0) {
$dur_string .= $dur_array['days'] . ' days ';
}
if ($dur_array['hours'] > 0) {
$dur_string .= $dur_array['hours'] . ' hours ';
}
if ($dur_array['mins'] > 0) {
$dur_string .= $dur_array['mins'] . ' minutes ';
}
if ($dur_array['secs'] > 0) {
$dur_string .= $dur_array['secs'] . ' secs ';
}
$myArray[$plate][] = array($inDateTime, $outDateTime, $inDate, $dur_string);
}
}
while ($startLoopDate < $endLoopDate) {
$dayString = strftime("%a, %d %B %Y", $startLoopDate);
$dayCheck = strftime("%Y-%m-%d", $startLoopDate);
print "<h2>$dayString</h2>";
print "<table width=\"100%\">";
print " <tr>";
print " <th>VRM</th>";
print " <th>Permit Group</th>";
print " <th>Entry Time</th>";
print " <th>Exit Time</th>";
print " <th>Duration</th>";
print " </tr>";
foreach($new_platelist as $wlPlate) {
if ($myArray[$wlPlate][0][2] == $dayCheck) {
print "<tr>";
print "<td>$wlPlate</td>";
if (isset($myArray[$wlPlate])) {
print "<td>".$staticWhitelistArray[$wlPlate]['groupname']."</td>";
print "<td>".$myArray[$wlPlate][0][0]."</td>";
print "<td>".$myArray[$wlPlate][0][1]."</td>";
print "<td>".$myArray[$wlPlate][0][3]."</td>";
}
else {
print "<td>Vehicle Not Seen</td>";
print "<td>Vehicle Not Seen</td>";
print "<td>Vehicle Not Seen</td>";
}
print "</tr>";
}
}
print "</table>";
$startLoopDate = $startLoopDate + $oneDay;
}
}
}

Can you echo this query so we can see what's actually being sent...
$sql = "
SELECT plate
, entry_datetime
, exit_datetime
FROM stats
WHERE plate IN ('$plate_lookup')
AND entry_datetime BETWEEN '$startDateTime' AND '$endDateTime'
AND carpark_id= '$cpId';
";
(This isn't an answer, but I wanted to make use of the additional formatting options)

Related

Calculeted time adding together in php (H:i:s)

I have a query which returns me some data.
//I loop through the query's result and write all data out
while($row =$result->fetch_assoc()){
echo $row['place'] . '|';
echo $row['gets_busy'] . '|';
echo $row['gets_empty '] . '|';
echo $row['time_between'] . '|';
echo "<br>";
}
ROOM01|2021-03-05 12:02:56|2021-03-05 12:04:02|00:01:06|
ROOM01|2021-03-05 12:05:42|2021-03-05 12:07:48|00:02:06|
ROOM01|2021-03-05 12:07:48|2021-03-05 12:12:54|00:05:06|
ROOM02|2021-03-05 12:15:54|2021-03-05 12:17:00|00:01:06|
ROOM02|2021-03-05 12:17:01|2021-03-05 12:23:17|00:05:16|
ROOM02|2021-03-05 12:23:59|2021-03-05 12:25:45|00:01:46|
I want something to write for the user like:
ROOM01 was busy for -> 00:08:18 during 2021-03-05
ROOM02 was busy for -> 00:08:08 during 2021-03-05
Can this be accomplished by PHP?
You can group into another array, by using the places and date as keys.
while($row = $result->fetch_assoc())
{
$place = $row['place']; // shortcut
$start = strtotime($row['gets_busy']); // start timestamp
$stop = strtotime($row['gets_empty']); // end timestamp
$time = $stop - $start; // duration in seconds
$date = date('Y-m-d', $start); // date for grouping
// group by place and date
if (!isset($data[$place][$date])) {
$data[$place][$date] = 0; // init with 0
}
$data[$place][$date] += $time; // add time.
}
// now, display data :
foreach ($data as $place => $dates) {
echo $place . ':<br>';
foreach ($dates as $date => $duration) {
$interval = new DateInterval('PT'.$duration.'S');
echo ' -> ' . $date . ' : ' . $interval->format('%h:%i:%s') . '<br>';
}
}

Why can't get the value of weekend in php

I don't know what are the errors of this code because it's suddenly not accurate the showing value to the user like this:
$holidays = array();
$query_holiday = "SELECT * FROM holiday_tbl";
$result = mysqli_query($dbcon, $query_holiday);
while($row_holiday = mysqli_fetch_assoc($result))
{
array_push($row_holiday, $holidays);
}
if(strtotime(date("Y-m-d")) > strtotime($row['due_date']))
{
$currentDate = date("Y-m-d");
$days = (strtotime($currentDate) - strtotime($row['due_date'])) / 86400;
$daysTemp = $days;
for($i=1;$i<$days;$i++)
{
$currentDay = date("D", strtotime("+ ".$i." days"));
$date_loop = date("Y-m-d", strtotime("+ ".$i." days"));
if($currentDay == "Sun" || $currentDay == "Sat")
{
$daysTemp--;
}
else if(in_array($date_loop, $holidays))
{
$daysTemp--;
}
}
echo $daysTemp;
}
The current implementation is rather convoluted. In these cases I find it's always better to start over and try to simplify the logic as much as possible. Here is my take on your problem:
function calculate_days_late($due_date = '', $holidays = array(), $current_date = 'today') {
$days_late = 0;
// Get the timestamps for due date and current date
$current_date_ts = strtotime($current_date);
$due_date_ts = strtotime($due_date);
// If current date is not after due date then not late
if ($current_date_ts <= $due_date_ts) {
return $days_late;
}
$loop_date_ts = $current_date_ts;
while ($loop_date_ts > $due_date_ts) {
// If the looping date is not a weekend or holiday then count it
if ( ! in_array(date('D', $loop_date_ts), array('Sat','Sun'))
&& ! in_array(date('Y-m-d', $loop_date_ts), $holidays)) {
$days_late++;
}
$loop_date_ts = strtotime('-1 day', $loop_date_ts);
}
return $days_late;
}
// Test
echo '2017-09-05 = ' . calculate_days_late('2017-09-05', array(), '2017-09-05') . "\n";
echo '2017-09-06 = ' . calculate_days_late('2017-09-05', array(), '2017-09-06') . "\n";
echo '2017-09-07 = ' . calculate_days_late('2017-09-05', array(), '2017-09-07') . "\n";
echo '2017-09-08 = ' . calculate_days_late('2017-09-05', array(), '2017-09-08') . "\n";
echo '2017-09-09 = ' . calculate_days_late('2017-09-05', array(), '2017-09-09') . "\n";
echo '2017-09-10 = ' . calculate_days_late('2017-09-05', array(), '2017-09-10') . "\n";
echo '2017-09-11 = ' . calculate_days_late('2017-09-05', array(), '2017-09-11') . "\n";
echo '2017-09-12 = ' . calculate_days_late('2017-09-05', array(), '2017-09-12') . "\n";
echo '2017-09-13 = ' . calculate_days_late('2017-09-05', array(), '2017-09-13') . "\n";
Working example: https://eval.in/856018

How to move page to the required path?

I make a php page in which i get data from bar but when i click cmd=7 and mode=test it moves cmd=default,how i set the links to the desired pages.
Here is my code:
function default1(){
$mode=$_GET['mode'];
if($mode=='')
{
$mode=$_POST['mode'];
}
$dates = array();
$timestamp = strtotime('-30 days');
for ($i = 0 ; $i <=30 ; $i++) {
//insert the date
$dates[$i]= date('m-d-Y', $timestamp);
//increase the day
$timestamp += 24 * 3600;
}
//print_r ($dates);
$strQuery="select DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y') as transaction_date,sum(amount)as Amount from transactions where mode='".$mode."' group by DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y')";
$result = $GLOBALS ['mysqli']->query ($strQuery) or die ($GLOBALS ['mysqli']->error . __LINE__);
while($rs=$result->fetch_assoc ())
{
$res[]=$rs;
}
//print_r ($res);
$strXML = "<chart caption='Reports of transactions' xAxisName='Date' yAxisName='Amount' showValues='0' useRoundEdges='1' palette='3'>";
for ($i = 0 ; $i <=30 ; $i++) {
foreach($res as $r)
{
if($r['transaction_date']==$dates[$i]){
$str = $r['transaction_date'];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='" .$r['Amount']."' />";
break;
}
else {
$str=$dates[$i];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='0' />";
}
}
$strXML .=$substrXML;
}
$strXML .= "</chart>";
return $strXML;
}
function past7days(){
//$mode=$_GET['mode'];
//if($mode=='')
//{
//$mode=$_POST['mode'];
//}
$dates = array();
$timestamp = strtotime('-7 days');
for ($i = 0 ; $i <=7 ; $i++) {
$dates[$i]= date('m-d-Y', $timestamp);
$timestamp += 24 * 3600;
}
$strQuery="select DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y') as transaction_date,sum(amount)as Amount from transactions WHERE transaction_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() and mode='".$mode."' group by DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y')
";
$result = $GLOBALS ['mysqli']->query ($strQuery) or die ($GLOBALS ['mysqli']->error . __LINE__);
while($rs = $result->fetch_assoc ())
{
$res[]=$rs;
}
$strXML = "<chart caption='Reports of transactions' xAxisName='Date' yAxisName='Amount' showValues='0' useRoundEdges='1' palette='3'>";
for ($i = 0 ; $i <=7 ; $i++) {
if(mysqli_num_rows($result)>0){
foreach($res as $r)
{
if($r['transaction_date']==$dates[$i]){
$str = $r['transaction_date'];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML.="<set label='".$transactiondate."' value='".$r['Amount']."' />";
break;
}
else {
$str=$dates[$i];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='0' />";
}
}
}
else{
$str=$dates[$i];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='0' />";
}
$strXML .=$substrXML;
}
$strXML .= "</chart>";
return $strXML;
}
if($_GET['cmd']=='' || $_GET['cmd']=='default' )
{
?>
<? echo date('M jS Y' ,strtotime($startdate)); ?> to <? echo date('M jS Y' ,strtotime($enddate)); ?>
<?
}
else
{
?>
<? echo date('M jS Y' ,strtotime($startdate)); ?> to <? echo date('M jS Y' ,strtotime($enddate)); ?>
<?
}
if($_GET['cmd']=='7')
{
?>
<span style="margin-left:10px;">Past 7 Days</span>
<?
}
else
{
?>
Past 7 Days
<?
try it
if($_GET['cmd']=='' || $_GET['cmd']=='default' )
{
echo date('M jS Y' ,strtotime($startdate))." To ".date('M jS Y' ,strtotime($enddate));
}
else
{
$url = "merchant/products/1/manage/reports?cmd=default&mode=".$_GET['mode'];
header("location:".$url);
exit;
}
if($_GET['cmd']=='7')
{
echo '<span style="margin-left:10px;">Past 7 Days</span>';
}
else
{
$url = "merchant/products/1/manage/reports?cmd=7&mode=".$_GET['mode'];
header("location:".$url);
exit;
}
<script type="text/javascript">
document.location.href = '/merchant/products/1/manage/reports?cmd=7&mode=<?php echo $_GET["mode"]; ?>';
</script>

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

Date is Echoing without 'echo' command - php

I have a form that is updated yearly, so a user inputs a date and other information then submits the form which gets stored in a database. When they come back a year later they do the same to overwrite the old records, the problem is is that when they come back the old date is being Echoed, which shouldn't happen. All of the other fields are blank which should happen. I'm not calling for the date to be echoed in the code but it still is.
Code for defining the date pulldown
// parameters: $fname - main name of field
// $date - actual date value from database
// $beginYear - first value in year list
// $endYear - last value in year list
// return: none
function make_date_pulldown($fname, $date, $beginYear, $endYear)
{
// read the date and break it up into $Year, $Month and $Day
// so that we can set the "SELECTED" in the option list
if ($date == ""){
// set some default values to be safe
$Year = 0;
$Month = 0;
$Day = 0;
} else {
$Year = (int) substr($date,0,4);
$Month = (int) substr($date,5,2);
$Day = (int) substr($date,8,2);
}
// need to build a table around these guys so that there won't
// be any word wrap... it's going to be a 1 row by 5 cols.
echo "<table border=0 cellspacing=0 cellpadding=0>\n";
echo "<tr>\n";
// build month list
echo " <td><font class=bluetext face=verdana,arial size=-2>\n";
echo " <center>Month<br>\n";
echo "<select name='month_$fname'>\n";
echo " <option value='00'></option>\n";
for ($i=1;$i<=12;$i++){
printf (" <option value='%02d'",$i);
if ($i == $Month) {
printf (" SELECTED");
}
printf (">%02d</option>\n",$i);
}
echo "</select>\n";
echo " </center>\n";
echo " </td>\n";
echo " <td><font class=bluetext face=verdana,arial size=-2>\n";
echo "/";
echo " </td>\n";
// build day list
echo " <td><font class=bluetext face=verdana,arial size=-2>\n";
echo " <center>Day<br>\n";
echo "<select name='day_$fname'>\n";
echo " <option value='00'></option>\n";
for ($i=1;$i<=31;$i++){
printf (" <option value='%02d'",$i);
if ($i == $Day) {
printf (" SELECTED");
}
printf (">%02d</option>\n",$i);
}
echo "</select>\n";
echo " </center>\n";
echo " </td>\n";
echo " <td><font class=bluetext face=verdana,arial size=-2>\n";
echo "/";
echo " </td>\n";
// build year list
echo " <td><font class=bluetext face=verdana,arial size=-2>\n";
echo " <center>Year<br>\n";
echo "<select name='year_$fname'>\n";
echo " <option value='0000'></option>\n";
for ($i=$beginYear;$i<=$endYear;$i++){
printf (" <option value='%d'",$i);
if ($i == $Year) {
printf (" SELECTED");
}
printf (">%d</option>\n",$i);
}
echo "</select>\n";
echo " </center>\n";
echo " </td>\n";
echo "</tr>\n";
echo "</table>\n";
}
Code for the PHP form on the website
<u>Date Of Submittal</u><br>
<?php
$startYear = date("Y")-1;
$endYear = date("Y")+1;
make_date_pulldown("submitdate", $submitdate, $startYear, $endYear);
?>
Looks like you want to create a drop down menu based on year ....
$date = new DateTime();
//Years
echo makeSelect($date->format("Y")-1, $date->format("Y")+1,$date->format("Y"));
//Month
echo makeSelect(1, 12,$date->format("m"));
//Day
echo makeSelect(1, $date->format("t"),$date->format("d"));
Function Used
function makeSelect($start, $end, $default = null) {
$content = "<select>";
$range = range($start, $end);
$selected = "";
foreach ( $range as $value ) {
$selected = ($default == $value) ? "selected" : null;
$content .= sprintf('<option value="%s" %s>%1$s</option>', $value, $selected);
}
$content .= "</select>";
return $content;
}
Figured it out, in my get_() function to call the database table I was reading the row for the submitdate and it was pulling and displaying the date based on that command and the function for make_date_pulldown.
Here is what that function looked like (obviously trimmed down):
<?
function get_submit($id, &$submitdate)
{
$query = "select * from submit where id = $id";
$result = mysql_query($query);
if ($result) {
$total_rows = mysql_numrows($result);
} else { $total_rows = 0; }
if ($total_rows > 0) {
$submitdate = trim(mysql_result($result, "", "submitdate"));
} else {
$submitdate = "";
$found = 1;
}
}
?>

Categories