Date to Zodiac sign and format date - php

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

Related

php get last year range date

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

Omitting redundant months and years in date range list

I have got strange issue with dates of events and I have tried hard to get it fixed but unable to do it.
I am attaching a screenshot of how I want to display the dates on the page :
In the picture the first event Deine Energie in Aktion! is a combination of 5 events with each event having its start date and end date.
The first part of the event is 1 day event which starts on 4th April and ends on 4th April. Similarly the second part is on 7th April, 3rd part on 9th April and 4th part on 20th April
The last part starts on 5th May and ends on 10th May.
The dates are stored in database in this format :
I am showing the dates for last part of event.
Event Start Date : 2013-05-05 00:00:00
Event End Date : 2013-05-10 00:00:00
So I want to display dates in the format shown in the picture.
There are multiple cases:
First is if all the dates are coming within a single month then we display the month name at the end only once.
Second is if months are changed then the month name will be shown after the date when the month is changed.
I am getting events dates in a while loop, so how do I compare the current event date with the coming event date in a loop.
This is the code I have used so far to get the dates from the database..
$nid = $row->nid;
$get_product_id = "SELECT product_id from {uc_product_kits} where nid='$nid'";
$res = db_query($get_product_id);
while ($get_product_id_array_value = db_fetch_array($res)) {
$prductid = $get_product_id_array_value['product_id'];
$start_date = db_query("select event_start,event_end from {event} where nid=%d",$prductid);
$start_date_value = db_fetch_object($start_date);
$end_value = $start_date_value->event_start;
$event_end_date = $start_date_value->event_end;
$TotalStart = date("d M Y", strtotime($end_value));
$TotalEnd = date("d M Y", strtotime($event_end_date));
$onlyMonthStart = date("M", strtotime($end_value));
$onlyMonthEnd = date("M", strtotime($event_end_date));
//$groupMonth = db_query("select event_start,event_end, month from {event} where nid=%d group by ",$prductid);
if($TotalStart == $TotalEnd ){
$startDay = date("d", strtotime($end_value));
$startMonth = date("M", strtotime($end_value));
if(in_array($startMonth,$newMonth)) {
echo $onlstartdate;
}
else {
$onlstartdate = date("d", strtotime($end_value));
echo $onlstartdate;
$tempStorage[] = $startMonth
}
//$newMonth[] = $startMonth;
}
}
Easiest would be to first collect all data from your query into e.g. array.
Only then iterate over the array. Having all data together will allow you to compare two consecutive date ranges to decide level of details you need to print for each.
Commented example:
// collect data from SQL query into structure like this:
$events = array(
array("event_start" => "2013-4-4", "event_end" => "2013-4-4"),
array("event_start" => "2013-4-7", "event_end" => "2013-4-7"),
array("event_start" => "2013-4-9", "event_end" => "2013-4-9"),
array("event_start" => "2013-4-20", "event_end" => "2013-4-20"),
array("event_start" => "2013-5-5", "event_end" => "2013-5-10"),
array("event_start" => "2014-1-1", "event_end" => "2014-1-2"),
);
// the actual code for range list generation:
for ($i = 0; $i < count($events); $i++)
{
// parse start and end of this range
$this_event = $events[$i];
$this_start_date = strtotime($this_event["event_start"]);
$this_end_date = strtotime($this_event["event_end"]);
// extract months and years
$this_start_month = date("M", $this_start_date);
$this_end_month = date("M", $this_end_date);
$this_start_year = date("Y", $this_start_date);
$this_end_year = date("Y", $this_end_date);
$last = ($i == count($events) - 1);
// parse start and end of next range, if any
if (!$last)
{
$next_event = $events[$i + 1];
$next_start_date = strtotime($next_event["event_start"]);
$next_end_date = strtotime($next_event["event_end"]);
$next_start_month = date("M", $next_start_date);
$next_end_month = date("M", $next_end_date);
$next_start_year = date("Y", $next_start_date);
$next_end_year = date("Y", $next_end_date);
}
// ranges with different starting and ending months always go
// on their own line
if (($this_start_month != $this_end_month) ||
($this_start_year != $this_end_year))
{
echo date("j M", $this_start_date);
// print starting year only if it differs from ending year
if ($this_start_year != $this_end_year)
{
echo " ".date("Y", $this_start_date);
}
echo "-".date("j M Y", $this_end_year)." <br/>\n";
}
else
{
// this is range starting and ending in the same month
echo date("j", $this_start_date);
// different starting and ending day
if ($this_start_date != $this_end_date)
{
echo "-".date("j", $this_end_date);
}
$newline = false;
// print month for the last range;
// and for any range that starts(=ends) in different month
// than the next range ends
if ($last ||
($this_start_month != $next_end_month))
{
echo " ".date("M", $this_start_date);
$newline = true;
}
// print year for the last range;
// and for any range that starts(=ends) in different year
// than next range ends
if ($last ||
($this_start_year != $next_end_year) ||
($next_start_month != $next_end_month))
{
echo " ".date("Y", $this_start_date);
$newline = true;
}
if ($newline)
{
echo " <br/>\n";
}
else
{
// month (and year) will be printed for some future range
// on the same line
echo ", ";
}
}
}
This outputs:
4, 7, 9, 20 Apr <br/>
5-10 May 2013 <br/>
1-2 Jan 2014 <br/>
A possibility to check if you need to print the month for the current date item is actually to check in the next item. Let me try to explain with pseudocode:
<?php
$month = 0; // Initialize $month variable to unset
// Loop over all your events
foreach($dates as $date) {
// Convert $date to a timestamp
// If the 'month' of the current $timestamp is unequal to $month
// it means we switch months and we have to print the $month first
if(date('m', $timestamp) != $month) {
echo $month; // Of course format how you want it to be displayed
// Set $month to the new month
$month = date('m', $timestamp);
}
// Print the rest of the event, like day numbers here
}
?>
Well, since you need to compare value from one loop to another, you won't be able to use echo directly.
You need to use temp variables. So with the first loop for the start date, you store $tmp_day_1 and $tmp_month_1 then with the end date loop you can compare both months and check if they are diferents. Then you can use echo. I hope I make my point :)

How to display converted time zones in a 'generic week' (Sunday thru Saturday)?

We are building a scheduling application wherein one user may set his "general availability" for all weeks like the following:
Sunday | Monday | ... | Friday | Saturday
When we ask a person A in India to indicate his "availability", we ask him to select from a drop down of values something like this:
12:00am
12:30am
01:00am
...
11:30pm
We ask him to select BOTH the "From" time (starting) and the "Till" time (ending).
What we SAVE in the database is JUST these values (see the following example):
user_id avail_day from to
1 Sunday 12:00:00 12:15:00
2 Monday 12:00:00 12:15:00
So, in essence, it looks like the following (in his LOCAL time zone)
(A)
Sunday | Monday | ... | Friday | Saturday
-----------------------------------------
| | | | 8:30am to 10:30am
As a separate piece of information, we know that he has selected to work in the IST (Indian Standard Time), which is presently GMT + 5:30 hours, so we can assume that the values he chooses are FOR the time zone he's presently in.
Now, for a person B on the East Coast, which is presently GMT - 4 hours (EDT), this time would be actually
Friday, 23:00:00 to Saturday, 01:00:00
We need help in figuring out how to:
(a) convert the earlier "text value" of the person A in IST to the local value of the EST person (NOTE that we know JUST the day and hours of availability as TEXT values)
(b) AND, then, we need to figure out how to display it on a "Standard week" beginning on a Sunday and ending on a Saturday.
What we want displayed should be something like this:
(B)
Sunday | Monday | ... | Friday | Saturday
--------------------------------------------------------------
| | | 11:00pm to 12:00am | 12:00am to 1:00am
Any smart ways of converting (A) into (B)?
Artefacto's code made into a generic function (Revision 2)
// This function should be used relative to a "from_date"
// The $from_timebegin and $from_timeend MUST be for the same day, not rolling over to the next
function shift_timezones_onweek3($from_timezone, $from_date, $from_timebegin, $from_timeend, $to_timezone)
{
$tz1 = new DateTimezone($from_timezone);
$datetime1 = new DateTime("$from_date $from_timebegin", $tz1);
$datetime2 = new DateTime("$from_date $from_timeend", $tz1);
$interval = $datetime1->diff($datetime2);
$indiaAvail = array(
array($datetime1, $datetime2)
);
$tz2 = new DateTimezone($to_timezone);
//convert periods:
$times = array_map(
function (array $p) use ($tz2) {
$res = array();
foreach ($p as $d) {
$res[] = $d->setTimezone($tz2);
}
return $res;
},
$indiaAvail
);
$res = array();
foreach ($times as $t) {
$t1 = reset($t);
$t2 = next($t);
if ($t1->format("d") == $t2->format("d")) {
$res[$t1->format("l")][] = $t1->format("g:ia") . " to ".
$t2->format("g:ia");
}
else {
$res[$t1->format("l")][] = $t1->format("g:ia") . " to 11:59pm";
$res[$t2->format("l")][] = "12:00am to ". $t2->format("g:ia");
}
}
return $res;
}
Your question doesn't make sense considering weekdays in the vacuum. These weekdays must be actual days, because the time conversion rules change along the year (DST) and through the years (politicians sometimes change the timezones and/or the date in which DST starts/ends).
That said, let's say you have you have a week availability plan for the first week of August, here defined as the week Aug 1 to Aug 7 2010:
<?php
$tz1 = new DateTimezone("Asia/Calcutta");
$indiaAvail = array(
new DatePeriod(new DateTime("2010-08-01 10:00:00", $tz1),
new DateInterval("PT2H15M"), 1),
new DatePeriod(new DateTime("2010-08-07 03:00:00", $tz1),
new DateInterval("PT8H"), 1),
);
$tz2 = new DateTimezone("America/New_York");
//convert periods:
$times = array_map(
function (DatePeriod $p) use ($tz2) {
$res = array();
foreach ($p as $d) {
$res[] = $d->setTimezone($tz2);
}
return $res;
},
$indiaAvail
);
$res = array();
foreach ($times as $t) {
$t1 = reset($t);
$t2 = next($t);
if ($t1->format("d") == $t2->format("d")) {
$res[$t1->format("l")][] = $t1->format("g:ia") . " to ".
$t2->format("g:ia");
}
else {
$res[$t1->format("l")][] = $t1->format("g:ia") . " to 11:59pm";
$res[$t2->format("l")][] = "12:00am to ". $t2->format("g:ia");
}
}
print_r($res);
gives
Array
(
[Sunday] => Array
(
[0] => 12:30am to 2:45am
)
[Friday] => Array
(
[0] => 5:30pm to 11:59pm
)
[Saturday] => Array
(
[0] => 12:00am to 1:30am
)
)
This may put in the same basket weekdays that are actually different days, but there's obviously no way to avoid it without explicitly indicating the day (or adding something like "Saturday (week after)" and "Saturday (week before)". This appears to be what you want, though.
How about this:
Ask user to provide his time zone (maybe you can even detect it by getting the user's location based on IP address, but the user still might want to change it)
Convert the provided time to you webserver's time and save it.
When displaying the time convert to the viewing user's time zone.
The Pear::Date package may help you doing this:
http://www.go4expert.com/forums/showthread.php?t=3494
Hope this helps,
Manuel
Use PHP's build-in DateTime class to do timezone conversions. Save the data in UTC to the database. When displaying your standard week schedule, use local timezone. To handle ±23 hours of timezone differences, you'll have to query 9 days (±1 days) from the DB before conversion.
Edit: To convert times to current user's local time, you need to get the timezone of each event. Join the scheduled events to user information for the user who made the event. This way you'll have the timezone from which to convert to the user's timezone.
The following pseudoish PHP will show:
$usersTZ = new DateTimeZone('EDT');
$now = new DateTime("now", $usersTZ);
$today = $now->format("Y-m-d");
$sql = "SELECT A.date, A.start, A.end, B.tz FROM schedule A JOIN users B ON (schedule.user_id = users.user_id) WHERE A.date BETWEEN '$sunday_minus_1_day' AND '$saturday_plus_1_day' ORDER BY A.date, A.start";
foreach ($db->dothequery($sql) as $event) {
$eventTZ = new DateTimeZone($event['tz']);
$eventStartDate = new DateTime("$today {$event['start']}", $eventTZ);
$eventStartDate->setTimeZone($usersTZ);
$eventEndDate = /* do the same for the end date */
if ($eventStartDate->format("Y-m-d") != $eventEndDate->format("Y-m-d")) {
/* create 2 events */
} else {
/* save the event to list of events with the new start and end times */
}
}
/* sort events, their order may be different now */
Of course, it would all be a lot simpler if you could save the start and end times with TZ to the DB and let the DB do all the hard work for you.

Check out that date is included in the period then 10 days following

I have a variable $ node-> field_work_start [0] ['view'] which denotes the date of birth. To follow up I want to do a background check on the fact that this date is included in the next period then 10 days from the current date. If true then x = 1, false x = 0. Help please with code PHP.
It sounds like you are given a DATETIME with $node->field_work_start[0]['view'] correct? If this is the case, we're going to convert it to a UNIX timestamp to make things a little bit easier. In this example we will assume your date is stored in M d, Y form.
This little code should work well for you!
<?php
class Node
{
// For sake of keeping things similar to your environment
var $field_work_start = array();
}
/**
* checkBirthday function
*
* The function will check a birth date
* and see if it is in the range of specified
* days.
*
* #param $birthday
* Birth date parameter. Assumed to be in M d, Y form
* #param $days
* The range of days to check where the birthday is
* #return int
* 0 if the birthday is _NOT_ within the proper range
* 1 if the birthday _IS_ within the proper range
*/
function checkBirthday($birthday,$days)
{
// Parse out the year of the birthday
$pos = strpos($birthday,",")+2; // Find the comma which separates the year
$today = strtotime(date("M, d")); // Check if day is < Dec. 22. If not, we need to account for next year!
// Check if the birthday is within the range and has not passed!
if($today < strtotime("Dec 22")){
$birthday = substr_replace($birthday,date("Y"),$pos,4); // Replace the year with current year
if(strtotime($birthday) <= strtotime("+".$days." days") && strtotime($birthday) >= time()){
return 1;
}
} else { // Less than 10 days left in our year.. check for January birthdays!
if(!strstr($birthday,"December")){
$birthday = substr_replace($birthday,date("Y")+1,$pos,4); // Replace the year with next year
$year = date("Y")+1;
} else { // Still December?
$birthday = substr_replace($birthday,date("Y"),$pos,4); // Replace the year with current year
$year = date("Y");
}
$day = (date("d")+10)-31; // 10 days from now is...
if((strtotime($birthday) <= strtotime("January ".$day.", ".$year)) && strtotime($birthday) >= strtotime("December 25, 2010")){
return 1;
}
}
return 0;
}
$node[] = new Node;
$node[0]->field_work_start[0] = "January 1, 1970"; // First birthday is _NOT_ within range
$node[1]->field_work_start[0] = "July 20, 1970"; // Second birthday _IS_ within range
for($i=0;$i<count($node);$i++){
if(!checkBirthday($node[$i]->field_work_start[0],10)){
print $node[$i]->field_work_start[0]." is not within the 10 day range.<br /><br />";
} else {
print $node[$i]->field_work_start[0]." is within the 10 day range.<br /><br />";
}
}
unset($node);
?>
It should return this output:
January 1, 1970 is not within the 10 day range.
July 20, 1970 is within the 10 day range.
Good luck!
Regards,
Dennis M.

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