...

View Full Version : Comparing dates with sql and dateAdd



Flic
07-28-2007, 06:14 AM
Hi,

I found a tutorial here (http://www.phpbuilder.com/columns/akent20000610.php3?page=6) which basically is a php version of asp and vb's dateAdd, and have been using it on a page of mine.

The idea is that the code will look at my database of items and only show those that have been added in the last 30 days, with the date stored in the db.

The code I have is:


$sql = 'SELECT * FROM item WHERE date > "' .dateadd("d",-30, getdate()). '"';


function DateAdd($interval, $number, $date) {

$date_time_array = getdate($date);
$hours = $date_time_array['hours'];
$minutes = $date_time_array['minutes'];
$seconds = $date_time_array['seconds'];
$month = $date_time_array['mon'];
$day = $date_time_array['mday'];
$year = $date_time_array['year'];

switch ($interval) {

case 'yyyy':
$year+=$number;
break;
case 'q':
$year+=($number*3);
break;
case 'm':
$month+=$number;
break;
case 'y':
case 'd':
case 'w':
$day+=$number;
break;
case 'ww':
$day+=($number*7);
break;
case 'h':
$hours+=$number;
break
case 'n':
$minutes+=$number;
break;
case 's':
$seconds+=$number;
break;
}
$timestamp= mktime($hours,$minutes,$seconds,$month,$day,$year);
return $timestamp;
}

The problem is that all of the items are showing not just the ones from the last 30 days. I've played around with it but nothing has made it work and most broke it more.

Any clues why it isn't working, or any alternative suggestions would be much appreciated!

Thanks!

CFMaBiSmAd
07-28-2007, 06:27 AM
Echo out your query sting $sql to see what it contains.

You are passing a getdate() result in the function call that is then used in a getdate() inside of the function, instead of a "date"

Edit: You can use mysql built in date and time functions directly in your query to accomplish the same thing without needing any of that PHP function code.

StupidRalph
07-28-2007, 08:07 AM
Edit: You can use mysql built in date and time functions directly in your query to accomplish the same thing without needing any of that PHP function code.
Didn't see your edit...:o Also, seems as if you should use mysql's DATE_SUB() instead of DATE_ADD().
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date-add



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum