php select query with different date formats - php

I have a variable called $date with a date format like 2012-01-30. On the other hand I have a field called srt_date_sortie in a mysql table. The format of that field is like 2012-01-30 11:31:00. I would like to select all records where $date and srt_date_sortie have equal dates not taking into consideration the time. Hope someone can help.
mysql_query("SELECT * FROM sorties WHERE srt_date_sortie = '$date'");
Here below how I build $date :
++$input;
$test=$input." days";
$date=date('Y-m-d', strtotime($test));
Thank you in advance for your replies. Cheers. Marc

For performance reasons you should avoid comparing against a derived column like DATE(srt_date_sortie) as this will prevent any indexes from being used. This negates a few of the solutions already posted.
The most efficient way of querying against your DATETIME field is by using a range query like:
mysql_query("SELECT * FROM sorties WHERE srt_date_sortie BETWEEN '$date 00:00:00' AND '$date 23:59:59'");
Unless you need all of the rows from the table the SELECT * could be inefficient, just list the rows that you need to retrieve.

Change your query with BETWEEN keyword for date start time and end time.

You can format date using DATE_FORMAT in mysql
mysql_query("SELECT * FROM sorties
WHERE DATE_FORMAT(srt_date_sortie,'%Y-%m-%d') = '$date'");

mysql_query("SELECT * FROM sorties WHERE DATE(srt_date_sortie) = '$date'");
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date

mysql_query("SELECT * FROM sorties WHERE srt_date_sortie LIKE '%2012-01-30%'");

$date=date('Y-m-d H:i:s', strtotime($test));
Use it

Check the TIMESTAMPDIFF mysql function
mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');
-> 3
mysql> SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01');
-> -1
mysql> SELECT TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01 12:05:55');
-> 128885

Related

comparing two fields in mysql

is their any query to pick certain date between two time stamps?The Problem is these two times stamps are set in two diffrent fields
SELECT * FROM table WHERE fs_from > theDate AND fs_to < theDate;
I suggest to use prepared statements and insert a date object into the query.
In my opinion you can try in this way (If I really understood your question)
SELECT myFields FROM myTable
WHERE myCertainDate BETWEEN fs_from AND fs_to
Try this:
SELECT *
FROM table
WHERE fs_from > 'some date'
AND fs_to < 'some other date'
Which date do you want? You can choose a random date by doing:
select t.*,
date_add(t.fs_from, interval cast(datediff(fs_to, fs_from) * rand() as int) day
) as ArbitraryDateBetweenTwoDates
from table t

Two appointments a week php

I have the following situation:
A patient is allowed to make 2 online appointments a week from today.
My code is:
$user_id = $_SESSION['id'];
$datum1 = date("d-n-Y");
$datum2 = date("d-n-Y", strtotime(date("Y-m-d", strtotime($datum)) . " +7 days"));
$query = "SELECT * FROM afspraken WHERE user_id='$user_id' AND datum BETWEEN '$datum1' AND '$datum2'";
The query with values:
SELECT * FROM afspraken WHERE user_id='2' AND datum BETWEEN '24-4-2012' AND '01-5-2012'
Still PhpMyAdmin gives 0 results whilst there are more then 10 records.
id user_id datum begintijd opmerking
55 2 24-4-2012 9:30 Deze afspraak is online gemaakt.
56 2 24-4-2012 10:00 Deze afspraak is online gemaakt.
Does someone see whats wrong in my queries?
Thanks in advance.
You can exclude date representation errors by leaving it to MySQL.
$query = "SELECT * FROM afspraken WHERE user_id='$user_id' AND datum BETWEEN CURRENT_DATE AND DATE_ADD(CURRENT_DATE, INTERVAL 1 WEEK)";
In general you probably need format 'YYYY-MM-DD'.
Another thing: your code is vulnerable for SQL injection. Use a prepared statement. They are nicer to read too, and escaping single quotes and backslashes in string fields etcera.
From the MYSQL Doc:
For best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type.
http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#operator_between
I would try casting the dates as DATE MySQL datatype in your WHERE clause.
So change you query to:
SELECT * FROM afspraken WHERE user_id='2' AND datum BETWEEN CAST('24-4-2012' AS DATE) AND CAST('01-5-2012' AS DATE);
For first check if in your database the field 'datum' is a date field.
Replace your query like this:
SELECT * FROM afspraken WHERE user_id='2' AND datum BETWEEN '24/4/2012' AND '01/5/2012'

getting current (system) day using an SQL query in PHP

I have this MySQl database that has a table which contains a column that contains days of the week like "Mon", "Tue" etc.
How do I get query the database and match this column content with the current (system) day?
like say
select .... where tablename.columnname = systemday
thanks.
Try using date_format(now(), "%a") as your condition value.
Read more here: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
Haven't you tried searching ?
Anyways i hope you want something like this,
$cur_day= date('D');
select .... where tablename.columnname = $cur_day;
WHERE tablename.columnname = substr(dayname(now()),1,3)
or
WHERE tablename.columnname = date_format(now(),'%a')
Note, however, that it may be affected by locale settings.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_weekday
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek
Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7 = Saturday). These index values correspond to the ODBC standard.
Example:
SELECT * FROM mytable WHERE dayOfTheWeek=WEEKDAY(NOW())
Also, you can do this using PHP`s strftime and date functions:
$query1 = mysqli_query('SELECT * FROM mytable WHERE dayOfTheWeek="'.date('N').'"');
$query2 = mysqli_query('SELECT * FROM mytable WHERE dayOfTheWeek="'.strftime('%u').'"');
But, I think, it is better to generate this in PHP-only way.
<?php
$day=date('D');
$sql='select * from the_table where the_table.'.$day.'=systemday';
?>

PHP: date between date

I have two dates:
10-11-2010 and 17-11-2010
Now i would like to SELECT all rows with the dates between those two.
How can I do that?
its very simple using between in where clause
, read more
select * from mytable where date between '10-11-2010' and '17-11-2010'
Sounds like a SQL question. Try the between condition.
$datefrom=date('Y-m-d');
$dateto=date('Y-m-d');
$sql = 'select * from mytable where depositdate between $datefrom and $dateto';

Selecting from a MySQL DB based on parts of a timestamp

Is there a way to select rows from a DB where the timestamp is in a certain year? I don't have a specific timestamp, just a range (ex. all timestamps within the year 2009). Is there a way to do this? How else might I go about doing something like this? Thanks for your help!
-iMaster
Use:
WHERE timestamp_col BETWEEN STR_TO_DATE('2009-01-01', '%Y-%m-%d')
AND STR_TO_DATE('2009-12-31', '%Y-%m-%d')
Any functions performed on a column mean that an index, if one exists for that column, can not be used.
I used the STR_TO_DATE function to ensure that whatever date provided as a string could be interpreted by MySQL as a TIMESTAMP.
Reference:
STR_TO_DATE
As simple as:
SELECT * FROM table WHERE YEAR(timestamp) = '1999'
Use FROM_UNIXTIME similar to this:
SELECT
FROM_UNIXTIME(my_timestamp, '%Y') AS year
FROM
table_name
WHERE
FROM_UNIXTIME(my_timestamp, '%Y') = 2009;
Where 'my_timestamp' is the name of your timestamp column.
Alternatively you can also convert it to a DATETIME
If you convert it to datetime you can do it by using the mysql DATE_FORMAT function which allows you to take a DATETIME and format it as a date. Then group by that column.
private function _formatDate() {
if ($this->_granularity == 'month') {
return '%y/%M';
}elseif($this->_granularity == 'day') {
return '%y/%M/%d';
}
}
public function getmyquery() {
$query = "
SELECT count( * ) as visits, DATE_FORMAT( `myOriginalDateField` , '".$this->_formatDate()."' ) AS mydate
FROM `mys`
WHERE id = ".$this->_Id."
GROUP BY mydate
ORDER BY mydate ASC
";
return $query
}
An important addition to the excellent suggestions already given here: if you plan on executing this query as a part of rendering your pages (as opposed to running this as a one-off report), you should really consider performance. Indexes won't help you much if you're post-processing the column value with a function before comparing it to something.
In that case, I would consider creating a separate database column that contains JUST the year, or just the month, etc.

Categories