2uzhan.com
Advertisement
Now Place:2uzhan.com » php working with dates

php working with dates

PHP @ October 31, 2010   Views:0

Hi Guys,

This is probably simple but I'm only learning php.

I'm doing a website which allows users to add details about upcoming events. What I would like to do is allow them to add the date of this event and once the date has passed the event is automatically removed from the database.

Is this possible?

Thanks in advance

--------------Solutions-------------

It's certainly possible, but probably more common would be to leave them in the database, and instead design your DB queries to only select those not in the past, e.g.:

Code:

SELECT * FROM events WHERE event_date >= CURDATE() ORDER BY event_date

If you assign and index on the event_date column (or whatever you want to call it), the above will process efficiently regardless of having many old records in the table.

That all makes sense. Thanks for that.

While I'm on it. I am having the user enter the date into a text box on the form. What is the best or correct way to allow a user to enter a date? How should the form be set up?

I usually prefer to use separate <select> elements for year, month, and day: each returning an integer. Then you can run those values through checkdate() to ensure the received number are valid. You can use PHP to help build the fields:

PHP Code:

<label>Month:<select name='month'>
<?php
$mos = array(1 => 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
foreach($mos as $num => $name)
{
   echo "<option value='$num'>$name</option>\n";
}
?>
</select></label>
<label>Day:<select name='day'>
<?php
foreach(range(1,31) as $day)
{
   echo "<option>$day</option>\n";
}
?>
</select></label>
<label>Year:<select name='year'>
<?php
for($yr = date('Y'), $max = $yr + 5; $yr <= $max; $yr++)
{
   echo "<option>$yr</option>\n";
}
?>
</select></label>

Then in the form-handler:

PHP Code:

if(checkdate($_POST['month'], $_POST['day'], $_POST['year']))
{
   // date is valid
}
else
{
   // date is NOT valid

thank you so much.

you have been a huge help.

it's all working perfectly

thanks again

Tags:
© 2018 2uzhan.com Contact