MySQL Query Interpret Date String as Date - php

I saw a couple of posts on this problem, but I'm not getting it to work correctly. I have a PHP variable that I initially POST as a string. To be able to handle a one week date range, I am converting this using strToTime into datetime format (e.g. July 22, 2013 echos as 1374476400).
My table has its dates stored as text in a Y-m-d format (e.g. July 22, 2013 is stored as 2013-07-22). I need to run a query comparing these two values to find dates that fall within my one week range, so I am trying to convert that text into datetime format for comparison purposes.
Here is the SQL that I am using:
$wk_begin = $_POST['wk_begin'];
$wk_begin = strToTime($wk_begin);
$wk_end = $wk_begin + 8;
$sql = "SELECT * FROM myTable WHERE (DATE(date)>=$wk_begin AND DATE(date)<$wk_end)";
I'm not getting any errors, but my query isn't picking any records up, even though i know that there are 7 matching records in the table. So I have two questions:
1) Is there a better way to go about this?
2) If I am on the right track, how can I get the sql statement to convert the text based dates into a big integer so that I can do the comparison correctly.
Any help is appreciated. Thanks!
EDIT: Thanks for all of the suggestions. I've changed the table so that the dates are stored in 'date' format (no more strings). Here is the updated code. Still not picking up any values:
$wk_begin = $_POST['wk_date'];
$wk_end = $wk_begin + 7;
$sql = "SELECT * FROM Workouts WHERE 'date' BETWEEN '$wk_begin' AND '$wk_end'";

date is a reserved word in mysql, to use it as a field name surround it in backticks.
Also your variable insertions need to be surround in apostrophes
SELECT * FROM myTable WHERE (DATE(`date`)>='$wk_begin' AND DATE(`date`)<'$wk_end'
A better solution (in addition to making the date field a date field) would be to use the db library's escaping and quoting mechanisms when building the sql statement.
Also since you are storing your dates in Y-m-d format the cast to date is unneccessary since string comparison on dates formated this way evaluate the same as the string. So
$sql = "SELECT * from myTable WHERE `date` >= ".$db->quoteAndEscape($wk_begin)." and `date` < ".$db->quoteAndEscape($wk_end);
UPDATE
Based on this date can be used as an unquoted field name.

<?php
$wkbegin = $_POST['wk_begin'];
$wk_begin = strToTime($wkbegin);
$d=date('j', $wk_begin)+8;
$m=date('n', $wk_begin);
$y=date('Y', $wk_begin);
$wk_end = date('Y-m-d', mktime(0,0,0, $m, $d, $y));
$wkbegin = date('Y-m-d', $wk_begin);
$sql = "SELECT * FROM `myTable` WHERE `date`>='".$wkbegin."' AND `date`<'".$wk_end."'";
?>

Related

get all today's event where the date is stored as int

i need help on this code..Im a newbie on this thing
i would like to query a table to get all today's event where the date&time is stored as int (eg: 1510876800)
i tried it like this
$time = time();
$changedate=date("Y-m-d", strval($time));
$today=strtotime($changedate);
$sql = "SELECT * FROM " . $xoopsDB->prefix('extcal_event') . " WHERE event_start='$today' ORDER BY event_organisateur ASC";
its not working because of the date in event_start have different time
How do i solve this ?
You are comparing unix timestamps so that will only match on the exact same second of that specific day.
If you have a unix timestamp stored, first you need to convert it to a mysql datetime value and then you can get the date part of it:
... WHERE DATE(FROM_UNIXTIME(event_start)) = :today ...
Here the value you bind to :today should have the Y-m-d format.
Note that I have used a placeholder for your variable as you should use prepared statements instead of injecting values directly into your query.

Comparing date() in sql query

I have 5 records in mysql database and these records have recorded date within this date interval.
$year=2015;
$month=8;
$datefrom=1;
$dateto=31;
$startdate='$year-$month-$datefrom 00:00:00';
$enddate='$year-$month-$dateto 23:59:59';
So I write a query to get these records out like this:
$sql = "SELECT id FROM newpost WHERE email=:email AND :startdate <= poststart <= :enddate AND postapproved=1";
Given that poststart column in table newpost has SQL Datetime format like this: "Y-m-d H:i:s".
But when I changed variable $year = 2016, I still got 5 results? It should return no record. Because those 5 records are recorded between 1 - 31 August 2015.
So I thought I did something wrong in the sql query especially the comparing date part but I could not configure out how to fix it?
Please help!
You can use BETWEEN in your query
$sql = "SELECT id FROM newpost WHERE email=:email AND (poststart BETWEEN :startmonth AND :endmonth) postapproved=1"
Use single quotes to wrap your date values
$sql = "SELECT id FROM newpost WHERE email=:email AND poststart BETWEEN ':startdate' AND ':enddate' AND postapproved=1";
A couple quick things to check to make sure it's not a syntactical error:
Your variable names don't match up. You defined startdate and enddate, but then in the query you used startmonth and endmonth.
You should probably also use leading zeros in your month and day, i.e.:
$month='08';
$datefrom='01';

How to fetch record by month in MySQL?

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' ";

Get data between two dates with date format unkown

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')`?

Using Date functions to pull records from database

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.

Categories