MYSQL Date range query not working correctly - php

I have a problem getting certain data from my database by querying a date range. In my database i have a DATE type field within the format YYYY-MM-DD. I want to get all data within a date range of today + 2 weeks (Expiring).
I have wrote:
$format = 'Y-m-j';
$date = date ( $format );
$new = date ( $format, strtotime ( '+14 day' . $date ) );
$start = date("Y-m-d", strtotime($new));
$today = date('Y-m-d');
$q = "SELECT * FROM listing WHERE dd_end BETWEEN '".$today."' AND '".$start."'";
while($row = mysql_fetch_assoc($q)){
$listing_id = $row['listing_id'];
echo "$listing_id";
}
So what I want to achieve is for the query to pull all the rows from now until 5th October. I've echo'd the variables and they show they're in the correct form (YYYY-MM-DD) to compare within the database but no results are returning.
Any help would be greatly appreciated. Many thanks in return.

Well, assuming that the mysql database has the same date that your server, you could let the mysql database do all the date calculations.
A little something like this:
SELECT *
FROM listing
WHERE dd_end BETWEEN CURDATE() AND (CURDATE() + INTERVAL 14 DAY)
On the other hand, i think Paul S's answer may fix your problem.
Edit:
You forgot to call mysql_query before the mysql_fetch_assoc() function.
$result = mysql_query($q);
while ($row = mysql_fetch_assoc($result))
{
$listing_id = $row['listing_id'];
echo "$listing_id";
}

If dd_end is a date you may want to read a certain section on the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
For best results when using BETWEEN with date or time values, use
CAST() to explicitly convert the values to the desired data type.
Examples: If you compare a DATETIME to two DATE values, convert the
DATE values to DATETIME values. If you use a string constant such as
'2001-1-1' in a comparison to a DATE, cast the string to a DATE.

May this is the right way ?
$start = date("Y-m-d", strtotime('+14 day' . $date));

Read:
http://php.net/manual/en/function.strtotime.php
strtotime has a second argument.
$format = 'Y-m-j';
$date = date ( $format );
$new = date ( $format, strtotime ( '+14 day' . $date ) );
$start = date("Y-m-d", strtotime($new));
Should be:
$new = strtotime('+14 day', time());
$start = date("Y-m-d", $new);
$today = date('Y-m-d');
$q = mysql_query("SELECT * FROM listing WHERE dd_end BETWEEN '".$today."' AND '".$start."'");
while($row = mysql_fetch_assoc($q)){
$listing_id = $row['listing_id'];
echo "$listing_id";
}

Related

PostgreSQL timestamp after converting to date, return date value - 01/01/1970

After inserting data from pstgrsql database I need to convert timestamp to date.
I tried php date() function but I only got value - 01/01/1970. Here is example of my code:
$query = "SELECT * FROM \"user\" WHERE verified= 't'";
$result = pg_query($conn, $query);
while ($row = pg_fetch_row($result)) {
$date = date('d/m/Y', $row[11]);
echo "\n";
echo "$row[0] , $row[1] , $row[3], $date ";
}
$ReportRow = array('date' => $date, 'activereg' => $activerag);
$ReportRow1 = array('date' => $date);
$ReportRow2 = array('date' => $date);
$report = array($ReportRow, $ReportRow1, $ReportRow2);
*there will be more data stored in these arrays but its just work in progress for now. Thanks all for any kind responses :)
EDIT 1
DB has rows like
`3125, alex, alex#example.com, 01/01/1970`
You are using date() to try to convert a string into a date, when date only accepts a full timestamp.
date(format,timestamp);
Rather, you want to convert your string in your result into a time value. Try
$time = strtotime($row[11]);
and if you need to switch it about use
$newformat = date('Y-m-d',$time);
If you need a timestamp after that, you can
$timestamp = $time->getTimestamp(); // Unix timestamp

Remove 1 week from date in php

Been a long while since I posted here, I have done a LOT of coding without having to ask but I am stuck :(
I have a variable which is called "$date", it is always the current date. Now I have logs which have a date set to them, now what I want to do is delete any logs that are older than a week from the current date. Here's how I'm doing it (? means I don't know what to put).
$date = date('Y-m-d H:i:s');
$one_week_old = $date - ?;
$clearlog = mysqli_query($con,"DELETE FROM logs WHERE logs.date < '$one_week_old'");
Instead of using another variable, you can just query it directly:
$clearlog = mysqli_query($con,"DELETE FROM logs WHERE logs.date <
dateadd(week,-1,getdate()));
You can do this:
$one_week_old = date("Y-m-d",strtotime("-1 week"));
$one_week_old = date('d-m-Y', strtotime("-1 week"));
$date = date('Y-m-d');
$newdate = strtotime ( '-1 week' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-d' , $newdate );
$query="DELETE FROM logs WHERE logs.date < '".$newdate." 00:00:00 '";
$clearlog = mysqli_query($con,$query);
If you don't need this date information later in PHP, i suggest you to do that directly in the MySql Query. Please consider, that this example will modify just the datepart, not the timepart of the current timestamp. It was't specified exactly if you like to to have whole days deleted or exactly the those data older then 604800 seconds (7 x 24 x 60 x 60 = 604800).
MySQL 5.5 Reference Manual 12.7 Date and Time Functions
mysqli_query($con, "DELETE FROM logs WHERE logs.date < DATE_SUB(NOW(), INTERVAL 1 WEEK)");
If you prefer Oriented Object paradigm, we have:
$oneWeekAgo = (new DateTime('-1 week'))->format('d/m/Y');
Explanation:
Return a new DateTimeObject
Set the timestamp from -1 week
Format to your need.

Date comparison with PHP and Mysql

I have a table with a date field type date.
What I am trying to do is to do a comparison between the date from inside the table and the today date. If the date from the table is yesterday then insert the today date.
The thing I'm not sure about is how to insert the data in the database so I can make the comparison. here is what im thinking to do"
$d = time();
$x = mysql_querry("SELECT date FROM table where id = $id", $con);
while($y = myqsl_fetch_array($x)){
$oldTime = $y['date'];
}
if ($oldTime < $d){
$i = mysql_querry("INSERT INTO table (date) VALUES (CURDATE()) ", $con);
}
So, I'm not sure if $oldTime and $d can be compared like that, but I hope you guys get my point.
Any ideas?
Thanks
You can't do in that way because the CURDATE() function return a date in a format like 2011-11-11 while time() returns the number of seconds since the January 1 1970 00:00:00 GMT.
Anyway you can change the format of the time() to look like the CURDATE() using the date() function in this way:
date('Y-m-d', time())
or even better, to get the current date, you can use just this line:
date('Y-m-d')
To conclude, you can do the if in this way:
if( strtotime($oldTime) < strtotime(date('Y-m-d')) )
or even better:
if( strtotime($oldTime) < strtotime('now') )
To compare dates you can use strtotime($date); Where date can be a time(), mysql date or date('Y-m-d'); string

Splitting Datetime into a date and a time value

Can someone give me a quick and dirty way to split a datetime (28-1-2011 14:32:55) into just the date (28-1-2011) and the time ( 14:32 ) or even better (2:32 PM) using PHP. Using a mySQL database as well.
Cheers
If you're using PHP > 5.2:
$myvalue = '28-1-2011 14:32:55';
$datetime = new DateTime($myvalue);
$date = $datetime->format('Y-m-d');
$time = $datetime->format('H:i:s');
Prior to PHP 5.2 mhitza gave a good answer.
In php you can use the date and strtotime functions for easy extraction.
$datetime = "28-1-2011 14:32:55";
$date = date('Y-m-d', strtotime($datetime));
$time = date('H:i:s', strtotime($datetime));
if your source of data is MySQL:
SELECT DATE( date_field ) AS date_part, TIME( date_field ) AS time_part ....
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_time
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date
Edit :
to answer the question from comments (example):
WHERE DATE( date_field ) > '2017-01-01'
One simple instruction will do the trick
explode will transform datetime to an array
and list will sort the datetime array into its needed values
$datetime = "28-1-2011 14:32:55";
list($date, $time)=explode(' ', $datetime);
// check the result
echo "date:". $date;
echo "<br>time:". $time;
// further more you can easily split the date into
// year month and day
list($year, $month, $day)=explode('-', $date);
If you looking for a really quick and dirty solution.
$datetime = "28-1-2011 14:32:55";
$date_arr= explode(" ", $datetime);
$date= $date_arr[0];
$time= $date_arr[1];
if you want to parse in the date from your Mysql and you want to remove time
then you can use this function
$date1=date("Y-m-d",strtotime('$your database field'))
We can easily split DateTime(28-1-2011 14:32:55) into date and time in MySQL.
select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",1) into #dateOnly;
select #dateOnly;
The output will be- 28-1-2011(Here we split the date from the DateTime)
select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",-1) into #timeOnly;
select #timeOnly;
The output will be- 14:32:55(Here we split the time from the DateTime)
We can covert the time to am and pm format also
select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",-1) into #timeOnly;
SELECT TIME_FORMAT(#timeOnly, "%h %i %s %p")into #time;
select #time;
The time format will become 02 32 55 PM

strtotime php mysql

All I'm trying to do is make the php file accumulate the end date from the sub date. I don't understand why this strtotime function isn't working. My database stores dates as "Y-m-d".
here's the code:
//disguised for security reasons
$db = mysql_connect("*******", "*******","********");
mysql_select_db("*******",$db);
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date!=null", $db);
while ($gad = mysql_fetch_array($getad)) {
$id = $gad['id'];
$asd = $gad['annual_sub_date'];
$aedate_time = strtotime('+1 year', $asd);
$aedate = date("Y-m-d", $aedate_time);
mysql_query("UPDATE members SET annual_end_date='$aedate', annual_active='Y' WHERE id='$id'");
}
---------SOLVED IT---------
I went and played XBox Split/Second for a bit and then realised the issue. My mind went back to PHP/MySQL 101. I coded everything right except the "!=null" part.
//Wrong Way
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date!=null", $db);
//Correct Way
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date IS NOT NULL", $db);
Now everything works :) That's the issues you can expect coding at 5:01am.
The first argument to strtotime is an absolute or relative date as a string, the second argument is an integer timestamp. You're giving it a relative date (string) as the first argument and an absolute date (also string) as the second. You need to convert $asd to a timestamp using strtotime first.
$aedate_time = strtotime('+1 year', strtotime($asd));
BTW, you could do the whole date calculation and updating in SQL with a single query, no need to take the long way around through PHP.
It's because strtotime requires timestamp as second argument and not string date in Y-m-d.
Just try code snippet below to see what I ment.
$gad = array('annual_sub_date' => '2010-11-21');
// wrong
// $asd = $gad['annual_sub_date'];
// good; convert to timestamp
list($year, $month, $day) = explode('-', $gad['annual_sub_date']);
$asd = mktime(0, 0, 0, $month, $day, $year);
$aedate_time = strtotime('+1 year', $asd);
$aedate = date("Y-m-d", $aedate_time);
echo $aedate . "\n";

Categories