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);
}
Related
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 {
}
?>
I have a user in a database with a creation_date. This user can run a job in my app UI, but he is limited by a number of job to run in one year.
This user has been created in 2014. I would like to do something like :
function runJob($user){
$nbRemainingJob = findReminingJobs($user);
if ($nbRemainingJob > 0){
runJob($user);
}
else {
die("no more credits";)
}
}
findReminingJobs($user){
$dateRangeStart = ?; //start date to use
$endRangeStart = ?; //end date to use
$sql = "SELECT count(*) FROM jobs WHERE user_id=?";
$sql .= "AND job_created_at BETWEEN ($dateRangeStart AND $endRangeStart)";
$res = $pdo->execute($sql, [$user->id]);
$done = $res->fetchOne();
return ($user->max_jobs - $done);
}
Every user's creation birthday, the $user->max_jobs is reset.
The question is how to find starting/ending date ? in other words, I would like to get a range of date starting from the user's creation date.
For example, if the user was created on 2014-04-12, my start_date should be 2018-04-12 and my end_date = 2019-04-11.
Any idea ?
First get the user register date from db and split it into Year, Month and Day like
$register= explode('-', $userCridate);
$month = $register[0];
$day = $register[1];
$year = $register[2];
Then get the current year like
$year = date("Y");
$dateRangeStart = $year."-".$month."-".$day; //start date to use
Now, check if this date is greater then today date, then use last year as starting date
$previousyear = $year -1;
$dateRangeStart = $previousyear ."-".$month."-".$day; //start date to use
$endRangeStart = date("Y-m-d", strtotime(date("Y-m-d", strtotime($dateRangeStart))
. " + 365 day"));
It is a idea, check if it work for you.
function getRange($registrationDate) {
$range = array();
// Split registration date components
list($registrationYear, $registrationMonth, $registrationDay) = explode('-', $registrationDate);
// Define range start year
$currentYear = date('Y');
$startYear = $registrationYear < $currentYear ? $currentYear : $registrationYear;
// Define range boudaries
$range['start'] = "$startYear-$registrationMonth-$registrationDay";
$range['end'] = date("Y-m-d", strtotime($range['start'] . ' + 364 day'));
return $range;
}
And for your example:
print_r(getRange('2014-04-12'));
Array
(
[start] => 2018-04-12
[end] => 2019-04-11
)
print_r(getRange('2014-09-13'));
Array
(
[start] => 2018-09-13
[end] => 2019-09-12
)
$created='2025-04-12';
$date=explode('-',$created);
if($date[0]<date("Y")){
$newDate=date('Y').'-'.$date[1].'-'.$date[2];
$dateEnding = strtotime($newDate);
$dateEnding = date('Y-m-d',strtotime("+1 year",$dateEnding));
}
else{
$newDate=$created;
$dateEnding = strtotime($newDate);
$dateEnding = date('Y-m-d',strtotime("+1 year",$dateEnding));
}
echo 'starting date is: '.$newDate;
echo '</br>';
echo 'ending date is: '.$dateEnding;
This code will get the date you have and match it with the current year. If the year of the date you provided is equal or above the current year the start date will be your date and end date will be current date +1 year. Otherwise if the year is below our current year (2014) it will replace it with the current year and add 1 year for the end date. Some example outputs:
For input
$created='2014-04-12';
The output is :
starting date is: 2018-04-12
ending date is: 2019-04-12
But for input
$created='2025-04-12';
The outpus is :
starting date is: 2025-04-12
ending date is: 2026-04-12
The solution that match my need :
$now = new DateTime();
$created_user = date_create($created);
$diff = $now->diff($created_user)->format('%R%a');
$diff = abs(intval($diff));
$year = intval($diff / 365);
if ($year == 0){
$startDate=$created_user->format("Y-m-d");
}else{
$startDate=$created_user->add(new DateInterval("P".$year."Y"))->format("Y-m-d");
}
The problem was to define the starting date that is comprised in the one year range max from the current date and starting from the user's creation date.
So if the user's creation_date is older than one year, than I do +1 year, if not, take this date. the starting date must not be greater than the current date_time
thanks to all for your help
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 database table that has two columns eventName|eventDate. I have created a function that takes in a startDate and endDate, I want to display the list of events in a ListView with each date as the header.
In my brief example below, I know I can retrieve the full event listings with SQL. How do I then slot the event headers in so that I can return them in a properly formatted array?
function retrieveEvents($startDate, $endDate) {
// run SQL query
//
if($stmt->rowCount() > 0) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// how do I write this part such that I can output event headers in my array
$events = $row;
}
}
}
So my intended output is
1st July 2013 ($startDate)
- Tea with President - 1300h
- Mow the lawn - 1330h
- Shave the cat - 1440h
2nd July 2013
- Shave my head - 0800h
3rd July 2013
4th July 2013 ($endDate)
- Polish the car - 1000h
In your MYSQL query:
SELECT * FROM `yourTableName` WHERE `eventDate` >= $startDate AND `eventDate` <= $endDate
PS: I'm not sure about the quotes arount the variables in your query.
PPS: never use * to select your columns, always only select the columns you need. Here I'm using it because I don't know the names of your columns
I ended up doing my checking in PHP and print a new row only when a different date is detected.
Codes below in case it serves someone's needs in future.
<?php
$currentPrintDay = 0;
$currentPrintMonth = 0;
$currentPrintYear = 0;
echo "<table>"
foreach($reservationsToShow as $row):
// get day, month, year of this entry
$timestamp = strtotime($row['timestamp']);
$day = date('d', $timestamp);
$month = date('m', $timestamp);
$year = date('Y', $timestamp);
// if it does not match the current printing date, assign it to the current printing date,
// assign it, print a new row as the header before continuing
if($day != $currentPrintDay || $month != $currentPrintMonth || $year != $currentPrintYear) {
$currentPrintDay = $day;
$currentPrintMonth = $month;
$currentPrintYear = $year;
echo
"<tr>" .
"<td colspan='100%'>". date('d-m-Y', $timestamp) . "</td>" .
"</tr>";
}
// continue to print event details from here on...
?>
Ok I have some code, gleaned from the internet. So this is the case and what I am trying to acheive.
Ok Page, user enters Birthday ( not Birthdate ) So we have the data in format dd/mm saved to database, example: 30/07 to represent 30 July )
So next page user goes to , I want to format the date correctly to match what I am trying to acheieve, add corresponding ordinal ( but remove the - between dd and mm ) and not echo the yy because we never got that information in the first place.
Essentially, if when user hits this page, we know the dd and mm , I am happy to add current year as the yy ( but not to fetch yy from the db ) but instead supply it adhoc.
The script below, is from internet and takes into account leap years, but need help. I cannot just remove the year, as this gives false results ( presumably because of strtotime function )But when user added their Birthday , we did not grab the year, because we do not need it.
Code:
<?php
function getStarSign($date="")
{
$zodiac[356] = "Capricorn";
$zodiac[326] = "Sagittarius";
$zodiac[296] = "Scorpio";
$zodiac[266] = "Libra";
$zodiac[235] = "Virgo";
$zodiac[203] = "Leo";
$zodiac[172] = "Cancer";
$zodiac[140] = "Gemini";
$zodiac[111] = "Taurus";
$zodiac[78] = "Aries";
$zodiac[51] = "Pisces";
$zodiac[20] = "Aquarius";
$zodiac[0] = "Capricorn";
if (!$date) $date = time();
$dayOfTheYear = date("z",$date);
$isLeapYear = date("L",$date);
if ($isLeapYear && ($dayOfTheYear > 59)) $dayOfTheYear = $dayOfTheYear - 1;
foreach($zodiac as $day => $sign) if ($dayOfTheYear > $day) break;
return $sign;
}
$myBday = "2013-07-30"; // this needs to be in English Australian format not American English format but do not need year
$AuEnBday = date("dS-F-Y", strtotime($myBday)); // this switches the date from USA to AU date format but do not need year
?>
The above echoes:Leo 30th-July-2013
I want to echo : Leo 30th July ( the year bit can be a var on page somehow but NOT from db )
// One more time!
$myBday = date("Y") . "-07-30"; // 2013-07-30
// Two digit year
$myBday2 = date("y") . "-07-30"; // 13-07-30