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 {
}
?>
Related
This question already has answers here:
Adding days to $Date in PHP
(12 answers)
Closed 5 years ago.
I have a table in MySQL with a date field (called NDate) which contains standard date values ("2017-04-17","2017-04-18", etc.).
Through PHP webpage, I am trying to take the system date (say today is 2017-04-17), and then pull all rows from the above table where NDate="2017-04-17". No issues till here.
I have a requirement to increment the day (starting today and going on for next 10 days - i.e. 2017-04-17 to 2017-04-26), and for each day report entries under a different heading like "Entries for 2017-04-17" which will list all rows having NDate 2017-04-17, "Entries for 2017-04-18" which will list all rows having NDate 2017-04-18.
I was trying to use a for loop with PHP date_modify function to increment the days one by one, but it is not showing any results.
Here are the selected pieces of code:
date_default_timezone_set('US/Eastern');
$datev = date("Y-m-d");
for ($x = 0; $x <= 10; $x++)
{
$datev=date_modify($date,"+$x days");
echo "before date format<br>"; // echo statement 1
echo "date is: $datev <br>"; // echo statement 2
$sql = "SELECT * FROM tablename where Ndate='$datev'";
echo "before result<br>"; // echo statement 3
...
...
...
}
Output on webpage shows only statement 1. But echo stats 2 and 3 are not printed.
You can increment days using strtotime function as a parameter to date function.
For 10 days, you can use for loop, to build an array of days. Then iterate over it, to execute queries you need.
$today = date('Y-m-d');
$dates=array($today);
for($i=1;$i<10;$i++) {
$NewDate=date('Y-m-d', strtotime("+".$i." days"));
$dates[]=$NewDate;
}
foreach($dates as $dt) {
// sql stuff here
echo "date is: $dt <br>";
$sql = "SELECT * FROM tablename where Ndate='$dt'";
echo "before result<br>";
// .....
}
This code should work for your case. If any problems, just let me know.
Try this:
$start = strtotime(date('Y-m-d'));
$end = strtotime(date('Y-m-d', strtotime('+10 days')));
while($start <= $end)
{
$date = date('Y-m-d', $start);
//use $date to do stuff
//SELECT * FROM tablename where Ndate='$date'
$start = strtotime("+1 day", $start);
}
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.
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);
I have a tricky one here.
I have a number of results in a table, this table has id, market, date and points.
I want to get all the records for a given month and then output all the points for each day, in order.
I'm not sure of the best way to do this? Her are my options, well my ideas, I could set a loop that will execute for every day of the given month, this will run a query to find every record for that day and will do this for every day of the month, this will then be easy to order a format the records but i'm thinking its not a good idea to query the database that many times.
The second idea i to query the database for all the records for that date, order them by the date. However i can see come problems here when outputting the information for each day, well it will be a long job then the first i think.
Any ideas? anyone done something like this before and could lend a helping hand? Any advise would be more than welcome!
Thanks.
while($row = mysql_fetch_array($getresults))
{
$day = FALSE;
foreach ($row as $row)
{
$day_res = date("Y-m-d H:m:s", strtotime($row["date"]));
if (!$day || $day != $day_res)
{
$day = $day_res;
echo '<h1>'.$day.'</h1>';
}
echo $row['date'] . " " . $row["id"] . ": " . $row["market"] .
"/" . $row["points"] . "<br/>";
}
}
This is the output i get from it:
1970-01-01 00:01:00
3 3: 3/3
3 3: 3/3
2012-01-13 09:01:06
E E: E/E
E E: E/E
1970-01-01 00:01:00
2 2: 2/2
2 2: 2/2
- -: -/-
- -: -/-
1970-01-01 00:01:00
4 4: 4/4
4 4: 4/4
and that more or less repeats for a while.
Thanks again.
If that date is only a date, then you could try something like this:
SELECT t.date, SUM(t.points) FROM table t WHERE date BETWEEN [STARTDATE HERE] AND [ENDDATE HERE] GROUP BY t.date
What it does? It selects everything the date & the sum of the points of that day, because we group all the results based on a day. So for every unique date in your table you will get a row with a result. Use the WHERE date statement to define from which month you need the selection.
Addition: the thing shown is only valid if date is in format like: YYYY-MM-DD. In case you have a timestamp (YYYY-MM-DD HH:ii:ss) you could try to change the query to:
SELECT t.date, SUM(t.points) FROM table t WHERE date BETWEEN [STARTDATE HERE] AND [ENDDATE HERE] GROUP BY DAYOFMONTH(t.date)
This ensures that you will group them by the day of the month (1 to 31) based on the dates from your table.
at first the query to get all for a given month ordered by date:
SELECT * FROM `table` WHERE `date` LIKE '2012-01%' ORDER BY date;
here the php loop to show it:
$day = FALSE;
foreach ($results as $result){
$day_res = date("d", strtotime($result["date"]));
if (!$day || $day != $day_res){
$day = $day_res;
echo '<h1>'.$day.'</h1>';
}
echo $result["id"].": ".$result["market"]."/".$result["points"]."<br/>";
}
Ok here for your structure:
$day = FALSE;
while($row = mysql_fetch_array($getresults))
{
$day_res = date("Y-m-d H:m:s", strtotime($row["date"]));
if (!$day || $day != $day_res)
{
$day = $day_res;
echo '<h1>'.$day.'</h1>';
}
echo $row['date'] . " " . $row["id"] . ": " . $row["market"] .
"/" . $row["points"] . "<br/>";
}
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);
}