php mysqli statement with time - php

I have the statement below that changes what is displayed depending on what time/day it is.
<?php $new = $mysqli->query("SELECT latedate FROM skiptonevents WHERE status='Active' ORDER BY id DESC LIMIT 1");
while($row = $new->fetch_assoc()) {
$late=$row["latedate"];
if($late < $datetime){
include_once('skiptonone.php');
}
else {
include_once('skiptontwo.php');
}
}
?>
In my database I have a column called latedate (0000-00-00 00:00:00).
$datetime = date('Y/m/d H:i:s');
I am trying to make it show (skiptonone.php) if todays date ($datetime) is less than latedate in the database ($late).
If latedate is after todays date to show skiptontwo.php
Could you please point me in the right direction as my current code does not work properly. It only shows skiptonone.php at the moment regardless of what time is in latedate.

Change
if($late < $datetime){
for
if(strtotime($late) < time()){
This is because you're doing string comparison otherway.

Related

Recommendation script not working when trying to combine both components

Context
I am building a simple recommendation script that serves to provide a user with the next upcoming date for a particular day of the week that he/she has booked the most.
(i.e. JohnDoe's most popular day to book is a Thursday, and the date of the next Thursday to come up is 2019/03/07)
This is what I am dealing with :
<?php
$date = new DateTime();
$date->modify('next thursday');
echo $date->format('Y-m-d');
?>
<?php require "snippets/get_booking_recommended_day.php" ?>
The first PHP code returns the next upcoming date for whatever day is asked. It works as it should. The PHP require references code from another folder that returns the users most popular day, in String format. (eg Monday, Tuesday). It also works.
My issue comes when trying to get the first bit of code to understand what is being returned from the 2nd bit of code.
I've attempted the following...
<?php
$date = new DateTime();
$date->modify('next' require "snippets/get_booking_recommended_day.php");
echo $date->format('Y-m-d');
?>
I've tried every variation possible. Nothing seems to work.
I'm quite new to PHP, and im 90% sure my coding practice is terrible but I am trying my best to grasp it - but so far this simple issue is beyond me.
Please help.
APPENDICES
Filename: snippets/get_booking_recommended_day.php
(Return the most booked day of the last 3 months by the user currently in session)
<?php
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
// Asks the qry: Of the last 90 days, what is the most booked day of the week for the current member in session?
// Min date is CURRENT_DATE() -100 instead of CURRENT_DATE() -30, because the MySQL function CURRENT_DATE() prints the date in an int format (YYYYMMDD) with no date formatting. Thus, to get the date a month ago, we must subtract this int by 100 so as to remove 1 from the 6th number in the series of numbers. Which is the 2nd M number.
$sql = "SELECT DATE_FORMAT(tbl_booking.booking_date, '%W'), COUNT(DATE_FORMAT(tbl_booking.booking_date, '%W')) AS mostpopularday
FROM tbl_booking
WHERE tbl_booking.member_ID=$_SESSION[member_ID]
AND tbl_booking.booking_date <= CURRENT_DATE()
AND tbl_booking.booking_date >= CURRENT_DATE() -300
GROUP BY DATE_FORMAT(tbl_booking.booking_date, '%W')
ORDER BY mostpopularday DESC
LIMIT 1";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["DATE_FORMAT(tbl_booking.booking_date, '%W')"];
}
} else {
// Return Nothing.
}
?>
Filename : pagebooking.php
(This is the datepicker that is located inside my pagebooking.php, its purpose is to choose the day of a booking. My hope is to populate this field with the recommended date that will be generated from the 2 PHP scripts above.).
<input name="new_booking_date" width="276" placeholder="Date" class="form-control input-md" type="date" max="<?php echo date("Y-m-d", strtotime("+30 day")); ?>" min="<?php echo date("Y-m-d", strtotime("+1 day")); ?>" required="" />
Issue resolved.
<?php
// If there are any values in the table, display them one at a time.
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
// Asks the qry: Of the last 90 days, what is the most booked day of the week for the current member in session?
// Min date is CURRENT_DATE() -100 instead of CURRENT_DATE() -30, because the MySQL function CURRENT_DATE() prints the date in an int format (YYYYMMDD) with no date formatting. Thus, to get the date a month ago, we must subtract this int by 100 so as to remove 1 from the 6th number in the series of numbers. Which is the 2nd M number.
$sql = "SELECT DATE_FORMAT(tbl_booking.booking_date, '%W'), COUNT(DATE_FORMAT(tbl_booking.booking_date, '%W')) AS mostpopularday
FROM tbl_booking
WHERE tbl_booking.member_ID=$_SESSION[member_ID]
AND tbl_booking.booking_date <= CURRENT_DATE()
AND tbl_booking.booking_date >= CURRENT_DATE() -300
GROUP BY DATE_FORMAT(tbl_booking.booking_date, '%W')
ORDER BY mostpopularday DESC
LIMIT 1";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$recommended_day = $row["DATE_FORMAT(tbl_booking.booking_date, '%W')"];
$date = new DateTime();
$date->modify('next '.$recommended_day);
echo $date->format('Y-m-d');
}
} else {
}
?>

PHP check if event has started

Im using the following mysql script to display a list of active / upcoming fixtures.
Select * FROM schedule
WHERE schedule.gameDate > CURDATE() OR
( schedule.gameDate = CURDATE() and schedule.gameTime > CURTIME() )
GROUP BY schedule.tournament
ORDER By schedule.gameDate
The above script works perfectly.
However, as an additional check to prevent a user from accessing a fixture which has expired im doing the following.
$curTime = date('H:i:s');
$curDate = date('Y-m-d');
$sql = "SELECT * FROM schedule
WHERE tournament = :tour AND weekNum = :round";
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':tour',$tournament);
$stmnt->bindValue(':round', $round);
$stmnt->execute();
$results = $stmnt->fetchAll();
foreach($results as $result){
echo $eventDate = $result['gameDate'];
echo $startTime = $result['gameTime'];
if($curDate > $eventDate){
echo '<h1> CURRENT ROUND ALLREADY STARTED</h1>';
die();
}//if
else if($eventDate==$curDate && $curTime>$startTime){
echo '<h1> CURRENT ROUND ALLREADY STARTED</h1>';
die();
}//else if
}//foreach
My Problem.
The loop never passes the first IF statment which always results to true...
DB Table
When I echo the variables I get the following:
$curTime = 09:30:00
$curDate = 2017-19-03
$eventDate = 2017-03-21
$startTime = 13:00:00
I realize it is not the prettiest code but according to my little experience and logic it should pass both if statments...
Any advise appreciated
Use strtotime() in compare two date in php
Replace if($curDate > $eventDate) with if(strtotime($curDate) > strtotime($eventDate)) and other comparison also
You can convert them to DateTime objects or timestamps to compare. String comparison will only check whether they are equal or not.
So:
$now = new DateTime();
$event = new DateTime($eventDate . ' ' . $startTime);
Then you can check whether dates are equal or later the same way you're already doing. See Example #2 on the Date Diff page of the php website. E.g. $now > $event, etc.
It should be elseif.not else if. There should not be a space between else and if.

Increment through date on week basis

I am building a php application using pgsql as its back end.
I would like to increment the date by some amount of date shich should be loaded from my database which have given value as available=1,3,5(implying monday,wednesday,friday of a week).I would like to increment these available values to current date. I am using N format in date() function to represent the values of days in a week as 1 to 7 which is stored in available field in the database
If current date =22-07-2013 which is monday,then i have to increment this to wednesday(available=3) and then to friday(available=5) And then to monday of the next week.
And so on..
but i cant do that..
i am in need of such a code where the value of available may change according to the tuples in that tuple.So i would like to increment the current date based on the value of available.
So please help me to achieve it.
The code I used is attached herewith.Please have a look at it.
<?php
$sq = "SELECT * FROM $db->db_schema.dept where active='Y' and dept_id=$dept_id";
$result = $db->query($sq);
$ftime=$result[0]['f_time'];
$ttime=$result[0]['t_time'];
$a=date('Y-m-d').$ftime;
$b=date('Y-m-d').$ttime;
$to_time = strtotime("$b");
$from_time = strtotime("$a");
$minutes= round(abs($to_time - $from_time) / 60,2). " minute";
$days=array();
$days= explode("," , $result[0]['available']);
$result[0]['available'];
$intl=$result[0]['slot_interval'];
$slots=$minutes/$intl;
$dt1 =date("m/d/Y $ftime ");
$s_mnts=explode(":",$ftime);
$m= date('N');
-- $dt=array();
$a=$dt1;
$l=0;
for($n=1;$n<=3;$n++)
{
for($k=$m;$k<=7;$k++)
{ $l=$l+1;
if(in_array($m,$days))
{
echo "dasdsa";
echo date("Y-m-d H:i:s", strtotime("$a +$l days"));
echo"<br>";
}
$m=$m+1;
if($m==7){$m=1;}
}
}
?>
where
dept_id -> primary key of the table dept
$db->query($sq); -> query is used to fetch the given values and is defined in another file named database.php in the program folder.
f_time and t_time -> fields in the table dept which describes the from_time and to_time.f_time is the time from which we have to start increment and t_time is the time to end this increment.
Please inform me whether there is any improvement in the code I have given. .
What you could do is something like this:
You say how many days you want to increment. And give an array of availables.
<?php
$inicialDate = time(); //Timestamp of the date that you are based on
$tmpDate = $inicialDate; //Copy values for tmp var
$increment = 5; //Increment five days
$available = [1,3,5]; //Days available
/*Ok, now the logic*/
while($increment > 0){
$tmpDate = strtotime("+1 day", $tmpDate); //Increase tmpdate by one day
if(in_array(date("N",$tmpDate), $available){ //If this day is one of the availables
$increment--;
}
}
$finalDate = date("m/d/Y",$tmpDate);
?>
This logic should work, although I don't know how to reproduce it via a SQL Procedure.
From what I can tell, you are after something like
UPDATE sometable
SET some_date_column = some_date_column + ('1 day'::INTERVAL * some_integer_value);

checking database for necessary updates using dateDiff

hey stackoverflowers. im having a few problems with the code i have written to check my database on refresh if all record dates on the database are between the specified $min and $max values. if not then the record will be updated. this is what i have done so far.
// check database for necessary updates
$update = mysql_query("SELECT * FROM rent");
while($row = mysql_fetch_array( $update )) {
$datetime_lower = DateTime::createFromFormat('d/m/Y', $min);
$datetime_upper = DateTime::createFromFormat('d/m/Y', $max);
$datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);
$diff_lower = $datetime_lower->diff($datetime_compare);
$diff_upper = $datetime_upper->diff($datetime_compare);
if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
// date is between min and max, do nothing
} else {
// date is not between min and max, update cell colour
$result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE $datetime_lower < $pDate && $datetime_upper > $pDate") or die(mysql_error());
}
}
the logic behind it seems rather rational but whenever i try to run the code i get the error message:
Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 41
Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 42
any idea whats going on?
fetching into $row but using $row_update
UPDATE rent SET colour='F0F0F0' will update ALL records if one tupel is not between $min and $max
Why not UPDATE rent SET colour='F0F0F0' WHERE pDate NOT BETWEEN $min AND $max MySQL Between
I think your approach is not optimized, instead of compare the different from php->mysql->php, you can issue a query to directly update to mysql, like
update rent set colour='F0F0F0' WHERE pDate>='$min' and pDate<='$max';

TV guide written in PHP - problems with datetime() and database functions

I'm creating a TV Guide which lists programmes coming up (and on some listings, previous airings from the past), with all data stored in a database. It runs in PHP, my version being 5.28 (upgrading to 5.30 or 6 soon).
Below is a script which works (note the field airdate is stored as DATETIME in the database):
[Disclaimer: The script isn't mine, but a generic one I downloaded, and modified to suit my own needs.]
<? //connect to mysql //change user and password to your mySQL name and password
mysql_connect("localhost","root","PASSWORD");
//select which database you want to edit
mysql_select_db("tvguide1");
//select the table
$result = mysql_query("select * from epdata3 order by airdate LIMIT 20;");
//grab all the content
while($r=mysql_fetch_array($result))
{
//the format is $variable = $r["nameofmysqlcolumn"];
//modify these to match your mysql table columns
$programme=$r["programme"];
$channel=$r["channel"];
#$airdate = strtotime($r['airdate']);
$airdate = strtotime($r['airdate']);
$now = strtotime("NOW");
$currentYear = date("Y", $now);
$yearOfDateFromDatabase = date("Y", $airdate);
if($yearOfDateFromDatabase == $currentYear)
$dateFormat = "F jS - g:ia"; // dateFormat = 24 December
else
$dateFormat = "F jS, Y - g:ia"; // dateFormat = 01 January 2010
$currentTime = date("g:ia", $airdate); // format of "Y" gives four digit year ie
2009 not 09
$airdateFormatted = date($dateFormat, $airdate);
$sDate = date("F dS, Y - g:ia",$airdate);
$episode=$r["episode"];
$setreminder=$r["setreminder"];
echo "<tr><td><b>$programme</b></td><td>showing on $channel</td>";
echo "<td>$airdateFormatted</td><td>$episode</td><td>$setreminder</td></tr>";
}
?>
That displays all the episodes coming up, and if there's any coming up the next year, it displays them with the year, like this:
TV Programme showing next on Channel1 December 30th, 2009 - 6:00pm "Episode 1 - Photosynthesis" Set Reminder
TV Programme showing next on Channel1 January 6th - 2:45pm "Episode 2 - Behind the Music" Set Reminder
TV Programme showing next on Channel1 January 7th - 8:00pm "Ultimate Car Crimes" Set Reminder
However, what I would like it to do is remove certain records after a period of time has expired (but that would have to be set somewhere in the script, since programme lengths vary) rather than me manually deleting them from the database. Some programmes are 30 minutes long, others 60 minutes... lengths vary, basically.
What I would like it to do is this (notice that the first listing does not show the date as it is the current date.):
TV Programme showing next on Channel1 6:00pm "CCTV Cities - Wigan" Set Reminder
TV Programme showing next on Channel1 January 9th - 2:45pm "Roman Empire - A History of its People" Set Reminder
TV Programme showing next on Channel1 January 10th - 8:00pm "Celebrity 100 Worst Moments" Set Reminder
but I don't know how to configure it to do this with PHP or the date() function. It works fine with the dates, and showing them.
I don't have access to cron jobs since this is on a localhost Apache installation on Windows Vista Home Edition.
If anyone could help me figure this out it would be much appreciated - all help is much appreciated.
I haven't put this as a live site, since it's "in development hell" right now, and I want to get things right as much as possible.
Your question is a bit unclear, but I assume you are asking how you can select only episodes from today or future, and how to format the date so that when the episode is airing today, show only the date.
Here's a revised version of your code that can handle both of those:
<?php
//connect to mysql
mysql_connect("localhost","root","PASSWORD");
mysql_select_db("tvguide1");
// Select only results for today and future
$result = mysql_query("SELECT * FROM epdata3 WHERE airdate >= CURDATE() ORDER BY airdate ASC LIMIT 20;");
while($r = mysql_fetch_array($result)) {
$programme = $r["programme"];
$channel = $r["channel"];
$airdate = strtotime($r['airdate']);
$episode = $r["episode"];
$setreminder = $r["setreminder"];
$now = time();
if(date('Y-m-d') == date('Y-m-d', $airdate)) {
// Same date, show only time
$dateFormat = 'g:ia';
} elseif(date('Y') == date('Y', $airdate)) {
// Same year, show date without year
$dateFormat = 'F jS - g:ia';
} else {
// Other cases, show full date
$dateFormat = 'F jS, Y - g:ia';
}
$airdateFormatted = date($dateFormat, $airdate);
echo "<tr><td><b>$programme</b></td><td>showing on $channel</td>";
echo "<td>$airdateFormatted</td><td>$episode</td><td>$setreminder</td></tr>";
}
?>
MySQL can literally handle millions of records - why bother deleting when you can archive..? Just don't show the archived records.
for listing future records instead of this:
$result = mysql_query("select * from epdata3 order by airdate LIMIT 20;");
I would suggest something like this:
$result = mysql_query("select * from epdata3 WHERE airdate > '$today' ORDER BY airdate LIMIT 20;");
For a gig listing page I years ago also added a delete algorythm fearing the db could get 'full' - but regretted it later...
function reldate ($time) {
$now = time();
$cmp_fmt = '%Y%m%d';
if (strftime($cmp_fmt, $time) == strftime($cmp_fmt, $now)) {
$out_fmt = '%I:%M %P';
} else {
$day = strftime('%e', $time);
if (preg_match('/([^1]1|^1)$/', $day)) {
$day_suffix = 'st';
} elseif (preg_match('/([^1]2|^2)$/', $day)) {
$day_suffix = 'nd';
} elseif (preg_match('/([^1]3|^3)$/', $day)) {
$day_suffix = 'rd';
} else {
$day_suffix = 'th';
}
$out_fmt = '%B %e' . $day_suffix . ' - %I:%M %P';
}
return strftime($out_fmt, $time);
}

Categories