Why does time() malfunction after midnight in my MySQL query? - php

I have two tables that my Query affects. The tables are called flightSched & Alteration. In both tables the arrivalTime column is of type TIME.
The query runs just fine until the $CurrentTimePlus4Hours variable elapses midnight. When this happens, the query doesn't yield any records, although the table has data ranging from all times of the day and night. Find below my code.
$currentDay = date('l');
$CurrentTimeMinus30min = date('H:i:s', strtotime('-30 minutes'));
$CurrentTimePlus4Hours = date('H:i:s', strtotime('+240 minutes'));
$query2 = "SELECT * FROM flightSched WHERE don = '$currentDay'
AND depOrArriv='Arrival'
AND arrivalTime BETWEEN '$CurrentTimeMinus30min' AND '$CurrentTimePlus4Hours'
ORDER BY arrivalTime ASC ;";
$query2 .= "SELECT * FROM Alteration WHERE don = '$currentDay'
AND depOrArriv='Arrival'
AND arrivalTime BETWEEN '$CurrentTimeMinus30min' AND '$CurrentTimePlus4Hours'
ORDER BY arrivalTime ASC ;";
/* execute multi query */
if ($mysqli->multi_query($query2)) {
do
{
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_array()) {
echo "<tr " . $variable . "><td>";
echo '<img src="php/displayImage.php?id=' . $row['id'] . ' "align="middle" width="110" height="35" >' . " "
. $row['flightNo'] ;
$flightNo = $row['flightNo'];
echo "</td><td>";
echo $row['airline'];
echo "</td><td>";
echo $row['origin'];
echo "</td><td>";
echo $row['arrivalTime'];
echo "</td><td>";
echo $row['status'];
echo "</td></tr>";
if ($variable == 'id=basicBoard')
{
$variable = 'class=alt';
//echo $variable;
}
elseif ($variable == 'class=alt')
{
$variable = 'id=basicBoard';
//echo $variable;
}
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
// printf("-----------------</br>");
}
}
while (#$mysqli->next_result());
echo "</table> <br/> <br/>";
}
I have tried to figure out why this happens but failed to fix the issue. Can someone kindly point out where I am going wrong in the code?

I think you just need to compensate for the time lapse by offsetting what the "current" day is:
$midnight = strtotime('today');
$now = time();
$tomorrow = $midnight + 86400;
$diff = $tomorrow - $now;
$offset = $now;
// Number of seconds in 240 minutes = 14400
if ($diff <= 14400) {
$offset += $diff;
}
$currentDay = date('l', $offset);
$CurrentTimeMinus30min = date('H:i:s', strtotime('-30 minutes'));
$CurrentTimePlus4Hours = date('H:i:s', strtotime('+240 minutes'));

Related

PHP loop HTML table for each user

I have a PHP loop which draws a table based off a MYSQLi query.
What i would like to do is create this table based on a userid (in my case the column called 'badgeid')
At the moment its creating one table
$sql = "SELECT first_name,last_name,signintime,signouttime FROM `signin_entries` WHERE iscleaner ='YES' AND signindate = curdate()";
$list_visitors_result=mysqli_query($con,$sql);
$count_visitors = mysqli_num_rows($list_visitors_result);
if($count_visitors != 0) {
while($row = mysqli_fetch_array($list_visitors_result)){
$signintime = $row['signintime'];
$signouttime = $row['signouttime'];
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo " <tr><td>$firstname $lastname</td>
<td>$signintime</td>";
if ($signouttime == ""){
echo "<td>Not Signed Out Yet</td>";
} else {
echo "<td>$signouttime</td>";
}
$timeFirst = strtotime(date("Y/m/d") . " " . $signintime);
$timeSecond = strtotime(date("Y/m/d") ." " . $signouttime);
//below checks if th second time is less than the first time than it must be from the day before so add 24 hours eg (signin time 23:30:00 signout time 07:30:30 would be 08:00:30 difference)
if ($timeSecond < $timeFirst)
{
$timeSecond = $timeSecond + 86400;
}
if ($signouttime == ""){
echo "<td>Cleaner Has Not Signed Out Yet</td>";
} else {
$differenceInSeconds = $timeSecond - $timeFirst;
echo "<td class='rowDataSd'>".converttime($differenceInSeconds)."</td>";
}
echo "</tr>";
}
}
//below function converts the seconds difference into hh:mm:ss format to the nearest second
function converttime($seconds) {
$t = round($seconds);
return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}
echo "<tr><th></th><th></th><th></th><th>Total Time Worked</th><tr><td></td><td></td><td></td><td class='totalCol'>Total:</td></tr>";
?>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
Which is great but i really need a table per 'badgeid'
You could do it like that:
$sql = "SELECT first_name,last_name,signintime,signouttime FROM `signin_entries` WHERE iscleaner ='YES' AND signindate = curdate() ORDER BY badgeid ASC";
$list_visitors_result=mysqli_query($con, $sql);
$count_visitors = mysqli_num_rows($list_visitors_result);
if ($count_visitors != 0) {
echo '<table>';
$current_badgeid = '';
while ($row = mysqli_fetch_array($list_visitors_result)) {
if ($current_badgeid == '') {
$current_badgeid = $row['badgeid']; //define if empty, for the first table
}
if($row['badgeid'] != $current_badgeid){
echo '</table><table>';
$current_badgeid = $row['badgeid'];
}
$signintime = $row['signintime'];
$signouttime = $row['signouttime'];
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo " <tr><td>$firstname $lastname</td><td>$signintime</td>";
if ($signouttime == "") {
echo "<td>Not Signed Out Yet</td>";
} else {
echo "<td>$signouttime</td>";
}
$timeFirst = strtotime(date("Y/m/d") . " " . $signintime);
$timeSecond = strtotime(date("Y/m/d") ." " . $signouttime);
//below checks if th second time is less than the first time than it must be from the day before so add 24 hours eg (signin time 23:30:00 signout time 07:30:30 would be 08:00:30 difference)
if ($timeSecond < $timeFirst) {
$timeSecond = $timeSecond + 86400;
}
if ($signouttime == "") {
echo "<td>Cleaner Has Not Signed Out Yet</td>";
} else {
$differenceInSeconds = $timeSecond - $timeFirst;
echo "<td class='rowDataSd'>".converttime($differenceInSeconds)."</td>";
}
echo "</tr>";
}
echo '</table>';
}
First, you add ORDER BY badgeid ASC to your query. Then you open a table before the loop starts, and you define a $current_badgeid var. Each time the badgeid changes, you close and reopen a table.

Putting Next 30 days into array

I am needing to find the next 30 days and put in array to repeat a scheduling code.
So I would need to have a variable for
$date= "would hold the date";
$day_of_week= "would hold the # value for the day of week";
I am at a loss of where to even start... I am wanting to repeat the following code for each respective day to schedule crews for the next 30 days.
<?
// Connection Script
include 'connection.php';
date_default_timezone_set("America/New_York");
$tomorrow= strtotime('+ 1 day');
$date= date('N', $tomorrow);
// Get all employees who work tomorrow and group by unit//
$units= "select e.user_id, e.station, e.full_name, max(e.level) level, es.unit, es.days, es.start_time, es.end_time from employees e
left join employee_schedule es on es.pid = e.user_id
where es.days like '%$date%' and e.status = 1
group by es.unit";
$units_result= $conn->query($units);
//Roll through all employees who work tomorrow and place then in appropriate unit.
while($row_unit = $units_result->fetch_assoc()) {
if($row_unit['level'] == 3){
$level= 1;
}elseif($row_unit['level'] == 4){
$level= 2;
}elseif($row_unit['level'] == 5){
$level= 3;
}elseif($row_unit['level'] == 8){
$level= 4;
}
//Get Unit ID from each group
$unitid = $row_unit['unit'];
$intime= date('Y-m-d', $tomorrow);
$intime= $intime.' '. $row_unit['start_time'];
$length= '+ 23 hours';
$intimes= strtotime("$intime");
$endtime= strtotime("$length","$intimes" );
$endtime= date('Y-m-d H:i:s', $endtime);
$station= $row_unit['station'];
$timenow= date('Y-m-d H:i:s');
echo "<p>I am scheduling unit number $unitid to be on at $intime and leave at $endtime </p>";
$unitinsert= "insert into schedules (date_time, unit, level_of_service, start_time, end_time, station)
values ('$timenow', $unitid, $level , '$intime', '$endtime', $station)";
if(mysqli_query($conn, $unitinsert)){
echo "Records inserted successfully.";
$unitinid= $conn->insert_id;
echo $unitinid;
} else{
echo "ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn);
}
$employee = "select e.*, es.unit, es.days, pc.email as pemail from employees e
left join employee_schedule es on es.pid = e.user_id
left join phone_carriers pc on pc.id = e.phone_carrier
where es.days like '%$date%'and es.unit = $unitid and e.status = 1";
$employee_result= $conn->query($employee);
if(mysqli_num_rows($employee_result) > 0){
while($row_employee = $employee_result->fetch_assoc()) {
$pid = $unitinid;
$eid= $row_employee['user_id'];
$ephone = $row_employee['mobile_number'];
$emailphone= $row_employee['mobile_number'].''. $row_employee['pemail'];
$unitcrewinsert= "insert into crew_assignment (date_time, pid, crew_member, phone_number, message_number, confirmed)
values ('$timenow', $pid, $eid , '$ephone', '$emailphone', 0)";
if(mysqli_query($conn, $unitcrewinsert)){
echo "Records inserted successfully.";
echo '<p> Crew Inserted </p>';
} else{
echo "<p>ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn).'</p>';
}
}
}
}
Your best bet is to provide a start date and an end date and get the number of days between them. Then it's just a matter of looping through each day and assigning it to an array. Could probably use the same logic to solve the weeks as well.
Example:
$d1 = Carbon::parse($start_date);
$d2 = Carbon::parse($end_date);
$num_days = $d1->diffInDays($d2) + 1;
$dates = array();
for ($i = 1; $i <= $num_days; $i++) {
array_push($dates, date('Y-m-d', strtotime($start_date.' +'.$i.' days')));
}
var_dump($dates);
I am not sure this is the best way, however it works.
<?php
include 'connection.php';
date_default_timezone_set("America/New_York");
// Start date
$date = '2018-05-18';
// End date
$end_date = '2018-05-31';
while (strtotime($date) <= strtotime($end_date)) {
$date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
$dayn = date('N', strtotime($date));
echo "<p> $date </p>";
echo "<p> $dayn </p>";
$units = "select e.user_id, e.station, e.full_name, max(e.level) level, es.unit, es.days, es.start_time, es.total_hours from employees e
left join employee_schedule es on es.pid = e.user_id
where es.days like '%$dayn%' and e.status = 1
group by es.unit";
$units_result = $conn->query($units);
//Roll through all employees who work tomorrow and place then in appropriate unit.
if($units_result->num_rows > 0){
while ($row_unit = $units_result->fetch_assoc()) {
if ($row_unit['level'] == 3) {
$level = 1;
} elseif ($row_unit['level'] == 4) {
$level = 2;
} elseif ($row_unit['level'] == 5) {
$level = 3;
} elseif ($row_unit['level'] == 8) {
$level = 4;
}
//Get Unit ID from each group
$unitid = $row_unit['unit'];
$intime = $date . ' ' . $row_unit['start_time'];
$total_hours= $row_unit['total_hours'];
$length = "+ $total_hours ";
$intimes = strtotime("$intime");
$endtime = strtotime("$length", "$intimes");
$endtime = date('Y-m-d H:i:s', $endtime);
$station = $row_unit['station'];
$timenow = date('Y-m-d H:i:s');
echo "<p>I am scheduling unit number $unitid to be on at $intime and leave at $total_hours </p>";
$unitinsert = "insert into schedules (date_time, unit, level_of_service, start_time, total_hours, station)
values ('$timenow', $unitid, $level , '$intime', '$total_hours', $station)";
if (mysqli_query($conn, $unitinsert)) {
echo "Records inserted successfully.";
$unitinid = $conn->insert_id;
echo $unitinid;
} else {
echo "ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn);
}
$inspectioninsert= ""
$employee = "select e.*, es.unit, es.days, pc.email as pemail from employees e
left join employee_schedule es on es.pid = e.user_id
left join phone_carriers pc on pc.id = e.phone_carrier
where es.days like '%$dayn%'and es.unit = $unitid and e.status = 1";
$employee_result = $conn->query($employee);
if (mysqli_num_rows($employee_result) > 0) {
while ($row_employee = $employee_result->fetch_assoc()) {
$pid = $unitinid;
$eid = $row_employee['user_id'];
$ephone = $row_employee['mobile_number'];
$emailphone = $row_employee['mobile_number'] . '' . $row_employee['pemail'];
$unitcrewinsert = "insert into crew_assignment (date_time, pid, crew_member, phone_number, message_number, confirmed)
values ('$timenow', $pid, $eid , '$ephone', '$emailphone', 0)";
if (mysqli_query($conn, $unitcrewinsert)) {
echo "Records inserted successfully.";
echo '<p> Crew Inserted </p>';
} else {
echo "<p>ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn) . '</p>';
}
}
}
}
}
}
?>

SQL Query only displaying first result rather than arrayed data

Basically I am building a calendar page that displays the months, and the days of the month(pulled from my database) and then any days that are inside the "start_date - end_date" variables are displayed with a different cell background color to the days that don't have a start or end date assigned, I have it working to an extent but it's only displaying the earliest of each months record rather than all the results.
ie.
2015-03-12(start) - 2015-03-16(end)
2015-03-03(start) - 2015-03-10(end)
And rather than display like this...
`1 2 [3 4 5 6 7 8 9 10] 11 [12 13 14 15 16] 17 18 19 20 ...`
it's just showing the [3 - 10] record, here is my current code..
<table width="100%" cellspacing="0">
<?php
$cmonth = date('F');
$cyear = date('Y');
$sql = "SELECT * FROM calendar WHERE year = '$cyear' ORDER BY m_order ASC";
$res = mysql_query($sql);
while ($rows = mysql_fetch_array($res)) {
$month_end = $rows['days_in_month'];
$month_name = $rows['month_name'];
$m_order = $rows['m_order'];
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
$row = mysql_fetch_assoc($res2);
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $days)
{
if(in_array($days, range($start, $end)))
{
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else
echo "<td align=\"center\">" . $days . "</td>";
}
?>
</tr>
<?php } ?>
</table>
Also I am aware of the dangers not using mysqli but I am just learning this on my local machine and plan on researching updated strategies once I get the functions working, so I'll know if my functions are broken or my coding is.
Thanks
try with common function to read data from table
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$cmonth = date('F');
$cyear = date('Y');
$sql = "SELECT * FROM calendar WHERE year = '$cyear' ORDER BY m_order ASC";
$res = mysql_query($sql);
while ($rows = mysql_fetch_array($res)) {
$month_end = $rows['days_in_month'];
$month_name = $rows['month_name'];
$m_order = $rows['m_order'];
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
$row = db_set_recordset($res2);
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $days)
{
if(in_array($days, range($start, $end)))
{
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else
echo "<td align=\"center\">" . $days . "</td>";
}
?>
</tr>
<?php } ?>
</table>
You are only fetching one row of your result set from your trips table. You need something like this to get the second one.
while ( $row = mysql_fetch_assoc($res2) ) {
/* process each row */
}
You're doing this right for your other result set. Take a look at the examples here: http://php.net/manual/en/function.mysql-fetch-assoc.php
You'll need to run through the result set rows and accumulate your "hot" days, then render the days just once. Something like this:
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
while ($row = mysql_fetch_assoc($res2)) {
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
$hot_days = array();
foreach(range(1, $month_end) as $days) {
$hot_days[$days] = 0;
if(in_array($days, range($start, $end))) {
$hot_days[$days] ++;
}
}
}
/* now you have a $hot_days array with nonzero values for interesting days */
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $day) {
if($hot_days[$day] > 0) {
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else {
echo "<td align=\"center\">" . $days . "</td>";
}
}
?>
</tr>
With respect, I don't have time to debug this.

How can I categorise MySQLi result set?

How can I change the code below so that I am only echoing each unique '$course' only once?
eg. currently my results look like =
ipswich-11:00-running
ipswich-12:00-flamingo rider
ipswich-14:00-lightning
norwich-13:10-ed is back
norwich-14:05-redrum
norwich-17:05-pickle
but I would like them to look like =
Ipswich
11:00-running
12:00-flamingo rider
14:00-lightning
norwich
13:10-ed is back
14:05-redrum
17:05-pickle
I thought about doing a mysqli query in a for each loop, but surely there is a better way?
My code =
<?php //connection block
if ($mysqli->connect_error) {die('Connect Error: ' . $mysqli->connect_error);}
$today = date("Ymd");
$query = "SELECT horse, course, time, date FROM dailytips WHERE date = $today ORDER BY course, time";
$result = $mysqli->query($query);
$today_uk = " " . date("d/m/y");
while($row = $result->fetch_array())
{ $rows[] = $row; }
echo "<h2>tips for" .$today_uk. "</h2>";
foreach($rows as $row)
{
$date = $row['date'];
$date = date("d/m/y", strtotime($date));
$horse = $row['horse'];
$time = $row['time'];
$course = $row['course'];
echo
'<div style= "width:600px; font-family:verdana;">
<div style="float:left; width:400px; margin-bottom:10px; margin-top10px;">
'.$row['course']. "-" .$row['time'] . "-" . $row['horse'] .'
</div>' ;
}
$result->close();
$mysqli->close();
?>
I guess you could nest a foreeach statement inside another.
so...
$query = "SELECT course, FROM dailytips WHERE date = $today ORDER BY course, time";
while($row = $result->fetch_array())
{ $rows[] = $row; }
echo "<h2>tips for" .$today_uk. "</h2>";
foreach($rows as $row) {
$query = "SELECT horse, time, date FROM dailytips WHERE course = $row['course'];
while($row = $result->fetch_array())
{ $rowDetail[] = $rowDetails; }
foreach($rows as $row) {
$date = $row['date'];
$date = date("d/m/y", strtotime($date));
$horse = $row['horse'];
$time = $row['time'];
$course = $row['course'];
echo
'<div style= "width:600px; font-family:verdana;">
<div style="float:left; width:400px; margin-bottom:10px; margin-top10px;">
'.$row['course']. "-" .$row['time'] . "-" . $row['horse'] .'
</div>' ;
}
}
I would consider putting your results in a table opposed to DIVs as this would seem to fit what you are trying to do much better. Set the table up before the loop and close once the loop has been exited.

Query just day month year from now()

I am inserting a date into a database with NOW() then I query the result. Here is the code.
function get_content($id = ''){
if($id != ''):
$id = mysql_real_escape_string($id);
$sql = "SELECT * FROM cms_content WHERE id = '$id'";
$return = '<p>Back to Content</p>';
else:
$sql = "SELECT * FROM cms_content ORDER BY id DESC";
endif;
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) != 0):
while($row = mysql_fetch_assoc($res)) {
echo '<h1> ' . $row['title'] . '</h1>';
echo '<p>' . stripslashes($row['body']) . '</p>';
**echo '<p>' . $row['date_posted'] . '</p>';**
}
else:
echo '<p> You broke it!, this post dosn\'t exsist!';
endif;
echo $return;
The
echo '<p>' . $row['date_posted'] . '</p>';
is where I echo the date. When I echo this from the database I get 2012-07-25 19:00:46, because that's what is in the database. My question is how would I echo the day, then echo the month, then the year. Ideally these would all be separate echos so I could style each differently.
This is alot more handy and less code.
$date = new DateTime($row['date_posted']);
$day = date->format('d');
$month = date->format('F');
$year = date->format('Y');
Resource: http://www.php.net/manual/en/class.datetime.php
Since the format is known, you can simply use this:
list($year,$month,$day) = explode("-",substr($row['date_posted'],0,10));
Then you can echo those variables however you want.
$date = strtotime($row['date_posted'];
echo date('d', $date);
echo date('m', $date);
echo date('Y', $date);
or
$date = new DateTime($row['date_posted']);
echo $date->format('Y');
etc
You would use php built in date() function: http://us.php.net/manual/en/function.date.php
echo "<p>".date('j M, Y', $row['date_posted'])."</p>";
// would output <p>25 July, 2012</p>
This can be modified into just about any format that you would like.
Another option is to do that directly in SQL, using the *date_format* function: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

Categories