I want to select everything where datetime field in MySQL equals today.
So the datetime field is like this: 2017-03-22 10:11:45
here is what I have:
$stmt = $dbh->prepare("SELECT * FROM list WHERE date_and_time = :date_and_time");
$stmt->bindParam(':date_and_time', $today???);
$stmt->execute();
how can i select the rows in my table where date_and_time equals today?
If you're just looking for today, you don't need to pass anything in. Just take advantage of MySQL's built-in functions:
$stmt = $dbh->query("SELECT * FROM list WHERE DATE(date_and_time) = CURDATE()");
This will format your date_and_time field to be in a Y-m-d format, and compare it to the current date.
Related
I have my datetime going into the DB like this:
$CurrentTime = time();
$DateTime = strftime("%b-%d-%Y %H: %M: %S", $CurrentTime);
In phpMyAdmin it looks like this:
May-15-2018 01: 04: 00
Feb-08-2018 13: 49: 23
etc...
The field is varchar(50)
I'm trying to extract posts from this table based on the month that the post was created.
I have tried the following:
"SELECT * FROM admin_panel WHERE MONTH(datetime) ='2'"
"SELECT * FROM admin_panel WHERE MONTH(STR_TO_DATE(datetime, '%b-%d-%Y %H: %M: %S')) ='2'"
I don't get an error, but nothing is returning. Any ideas on how I can correct this?
You can use MYSQL STR_TO_DATE with MONTH
"SELECT * FROM admin_panel WHERE MONTH(STR_TO_DATE(`datetime`,'%b-%e-%Y %H:%i:%s')) = 5"
Adding Year with AND condition
SELECT * FROM admin_panel WHERE MONTH(STR_TO_DATE(`datetime`,'%b-%e-%Y %H:%i:%s')) = 5 AND YEAR(STR_TO_DATE(`datetime`,'%b-%e-%Y %H:%i:%s')) = 2018
The following works when the 'datetime' column is defined as DATETIME, yyyy-mm-dd h:i:s (2018-06-14 14:29:15) and not as VARCHAR,
SELECT * FROM admin_panel where extract(month from datetime)='02'
I think, if you use a VARCHAR instead of a DATE.. type, then you will have to typecast string to a date for performing any date-based functions on it in a query. Imo, it is better to have date stored in DATE.. format and let MySQL store it in some format; but you could format it using DATE_FORMAT functions for displaying.
When column type is DATETIME, month() call also can be used as in,
SELECT * FROM admin_panel WHERE month(datetime)='02'
I have been trying for a while, read countless stackoverflow answers and still cant crack it!
I have a table in my db with a field called dob. This field is currently just a TEXT field (but i have since tried changing it to a DATE field and still cant get it to work).
The DOB field's data is in this format (UK dates) - 22/05/2016.
Im trying to find out the number of users who's birthdays are between two dates.
For example, anyone who was born in the last two years:
$twoyearsago=date('d/m/Y', strtotime("-2 years"));
$today = date("d/m/Y");
$sql = mysql_query("SELECT * FROM users WHERE dob >= '" . $twoyearsago . "' AND date <= '" . $today . "' ORDER by id DESC");
I also tried:
$sql = mysql_query("SELECT * FROM users WHERE dob BETWEEN '" . date('d-m-Y', strtotime($twoyearsago)) . "' AND '" . date('d-m-Y', strtotime($today)) . "'";
Hopefully you can see where me logic is and hoping you will see where im going wrong - any help would be appreciated.
Jack
With STR_TO_DATE can you convert your date
NOTE: i have changed the Column type from TIMESTAMP to DATE, because in a TIMESTAMP you can store date before 1970-01-01.
SELECT STR_TO_DATE('22/05/2016','%d/%m/%Y');
sample
MariaDB [bb]> SELECT STR_TO_DATE('22/05/2016','%d/%m/%Y');
+--------------------------------------+
| STR_TO_DATE('22/05/2016','%d/%m/%Y') |
+--------------------------------------+
| 2016-05-22 |
+--------------------------------------+
1 row in set (0.00 sec)
MariaDB [bb]>
so you can change you Table
ALTER TABLE `users`
ADD COLUMN new_dob DATE;
UPDATE `users` SET new_dob = str_to_date(dob,'%d/%m/%Y');
** Verify the dates
ALTER TABLE `users`
DROP COLUMN dob;
ALTER TABLE `users`
CHANGE COLUMN `new_dob` `dob` DATE;
** CREATE an INDEX for perfomance **
ALTER TABLE `users`
ADD KEY (`dob`);
SELECT
SELECT * from `users` where dob between '2014-01-01' AND `2015-08-01';
The problem with many local date formats is that their lexical and chronological order are different (eg, 16-11-2016 comes after 11-12-2016 lexically, but before chronologically). That's why storing dates in string fields in some regional format is in most cases a bad idea: you will get sorting issues sooner or later.
Next, when specifying dates literally for MySQL, you have to respect certain formats, as explained in the documentation
Putting that into practice, the range variables should look something like this:
$today = date("Y-m-d");
$twoyearsago=date("Y-m-d", strtotime("-2 years"));
Then we use a built-in function str_to_date to convert the string column into a date that can be compared correctly:
SELECT * FROM users WHERE
STR_TO_DATE(dob, '%d/%m/%Y') between '$twoyearsago' and '$today'
This will work, but in the long run you're much better off converting that dob column into a real date format (as #BerndBuffen shows) as it's clearer, easier to internationalize and a lot better performing.
Sidenote: you are still using the long-deprecated mysql_ extension. You should really switch to either mysqli_ or PDO.
You need to build your query by using actual date values, not string. So you need format YYYY-MM-DD in query - both side of the comparison.
Try following.
$twoyearsago=date('Y-m-d', strtotime("-2 years"));
$today = date("Y-m-d");
$sql = mysql_query("SELECT * FROM users WHERE STR_TO_DATE(dob, '%d/%m/%Y') >= '" . $twoyearsago . "' AND STR_TO_DATE(dob, '%d/%m/%Y') <= '" . $today . "' ORDER by id DESC");
STR_TO_DATE(dob, '%d/%m/%Y') makes sure your d/m/Y saved dob string value to be converted to date in the query that MySQL can understand and compare with the given YYYY-MM-DD values.
Actually the proper way is creating a date field and transferring dob string values as date to this new field by using the same function unless you will always get the date values as string into the dob field.
Another method is to use DateTime and format the date before doing your query.
$begin = '10/02/2014';
$emd = '10/02/2015';
$beginDate = DateTime::createFromFormat('d/m/Y', $begin);
$emdDate = DateTime::createFromFormat('d/m/Y', $emd);
$stmt = "
SELECT
...
FROM users
WHERE birthday >= '".$beginDate->format('Y-m-d')."'
AND birthday <= '".$endDate->format('Y-m-d')."'
";
I have stored Date in database in dd-mm-yy format, for example 03-10-2013,
How to search record by month? Month in digit (01 to 12);
I am using currently
$query = "SELECT * FROM data WHERE date LIKE %$month%";
but this not working properly.
I am assuming when you say dates as stored in the database in a format, that they are not stored using a "date" type and instead are using a varchar or char type for the column.
Based on that there are few ways to do this.
Leave the database as it is and convert values on the fly.
SELECT * FROM data WHERE Month(STR_TO_DATE(datestrcolumn, '%d/%m/%Y')) = 5;
Change the type of the column to a "date" type column
SELECT * FROM data WHERE Month(realdatecolumn) = 5;
Change the type of the column to a "date" type column, store a separate column for the month.
UPDATE data set monthcolumn = Month(realdatetimecolumn)
then
SELECT * FROM data WHERE monthcolumn = 5;
Create an index on monthcolumn and this query will be much faster than the other queries if there is a lot of data
Fix the date format in your database structure first, change it to: yyyy-mm-dd
Then change your query statement to:
$query = "SELECT * FROM data WHERE MONTH(`date`) = '$month';
This will select the month as '5' or '11' or '12' which will give duplicates for differing years.
If you need the month with year (to avoid duplicate years):
$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),1,7) = SUBSTR(DATE('$month'),1,7);
This will return: '2015-01' or '2014-12'
To get date as '01' or '04' or '12':
$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),6,2) = SUBSTR(DATE('$month'),6,2);
Try this...
You could use MySQL MONTH() function
MySQL MONTH() returns the MONTH for the date within a range of 1 to 12 ( January to December). It Returns 0 when MONTH part for the date is 0
4 is april
SELECT * FROM tbl WHERE MONTH( date ) ='4'
You can do like it... as it is not in date format(YYYY-MM-DD)
$q="SELECT * FROM data WHERE MONTH(DATE_FORMAT(STR_TO_DATE(date, '%d-%m-%Y'), '%Y-%m-%d') ) = '$YOUR_SEARCH_MONTH' ";
date format: init(11)
date column value: 1421382119
I have managed to get the dates from the table.
$sqllast = $Db1->query("SELECT * FROM table");
while($row = $Db1->fetch_array($sqllast))
{
$date1 = date('Y-m-d', $row['create']);
echo "$date1";
}
Question:
I want to get values from this table using the dates interval. I am not getting idea which format shall I enter the dates.
I have tried y-m-d, d-m-y , but it did not work
I tried this query
SELECT * FROM table WHERE create between '2015-01-1' and '2015-01-30'
Since the column type is int, you have to convert your string dates to ints as well.
Try this:
SELECT * FROM `table` WHERE `create` BETWEEN UNIX_TIMESTAMP('2015-01-01') AND UNIX_TIMESTAMP('2015-01-30')
Since you are storing a unix_timestamp as your value in column create, you will want to use MySQLs UNIX_TIMESTAMP() to covert your dates to a unix_timestamp
SELECT * FROM table WHERE create between UNIX_TIMESTAMP('2015-01-1') and UNIX_TIMESTAMP('2015-01-30')`?
I'm truly stumped on something - I have a table in my database with a column called 'today' that has Date and Time records. The column has entries that look like this:
October 25, 2014, 4:58 am
October 25, 2014, 4:36 am
I'm having trouble pulling the rows by date; I think the time stamp is messing with the MySQL query. And I need an SQL query to pull any records where the variable $today matches the date information in the column 'today'. This doesn't work:
$today = date("F j, Y"); // looks like this: October 25, 2014
$result = mysqli_query($link,"SELECT * FROM records WHERE today = $today"); // 'today' represents the column in the table
while($row = mysqli_fetch_array($result)) {
echo var_dump($row);
}
I just get an empty result, I think due to the time stamp. Can someone advise on a better MySQL query that will only grab the rows where $today matches the date in the 'today' column?
Although storing the date and time as string in varchar is not really a good idea, you could still alter your query to match string containing the current date with a LIKE statement:
$result = mysqli_query($link,"SELECT * FROM records WHERE today LIKE '$today%'");
That is just to get your current setup working as a temporary fix but i highly suggest you take a look at datetime and timestamp or similar date types if this is a serious project and not just playing around. with programming.
UPDATE
With a datetime you could get the dates which are the same as today with:
SELECT * FROM `records` WHERE `today` = CURDATE();
with a timestamp you would need to pass it as date so your query would be:
SELECT * FROM `records` WHERE date(`today`) = CURDATE();
You can just use the MySQL date functions:
SELECT *
FROM records
WHERE today = CURRENT_DATE;
If there is a time component on the today column, then the best structure is:
SELECT *
FROM records
WHERE today >= CURRENT_DATE and today < date_add(CURRENT_DATE, interval 1 day)
It's obvious that both dates are not equal. Both dates are treated like text values and are not equal. You need to convert the column containing date in your MySQL query as such:
$result = mysqli_query($link,"SELECT * FROM records WHERE DATE_FORMAT(today, '%F %j, %Y') = $today");
Note that you have to change your column to store values of the type of DATE. Or just use queries as proposed in other answers.