php mysql comparing dates for equality - php

I am using php to access fields from 2 tables.
This part works just fine
$sql=mysql_query('SELECT * FROM user_weeks WHERE user_id = '.$_SESSION["user_id"].' ORDER BY date DESC') or die(mysql_error());
I get the date just fine by doing this
$infodate=$info["date"];
echo $infodate;
However I'm trying to take that date and compare it to one in a different table as such
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE date = '.$infodate.' ') or die(mysql_error());
however, that gives me no results. I'm a noob so sorry if this code is so "2000 and late"

Assuming both date fields are of type date, you need to wrap the name date in backticks, since date is a reserved word and you need to wrap your date in quotes.
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE `date` = "'.$infodate. '"') or die(mysql_error());
Also, mysql_* functions are deprecated. You need to look into using PDO or mysqli to query your database.

date is reserved word use to wrap inside the backtick `date
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE `date` = "'.$infodate.'" ') or die(mysql_error());

Presumably you're using a standard yyyy-mm-dd type date string in your query, which means you're lacking quotes around the date value:
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE date = '.$infodate.' ')
^--here ^-- here
Your query will look like
... WHERE date = 2013-12-18
and be evaluated as a simple mathematical subtraction:
... WHERE date = 1983
You need quotes:
.... date = "' . $infodate . '"');
^-- ^--

Related

Select between dates from table - strtotime?

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

Select rows between two dates where dates are variables

I have an SELECT statement in php and I need to select all rows of the table where the "date" column is in between a start date and end date that will be defined by variables.
I have this working perfectly fine when I define the dates directly in the SELECT statement as shown below:
date BETWEEN "2015-02-03" AND "2015-02-05"
However, when I try to do the same thing but with variables, it doesn't seem to work:
date BETWEEN "$startdate" AND "$enddate"
Where
$startdate = "2015-02-03";
$enddate = "2015-02-05";
Hope all this makes sense, Cheers in advance.
Full code snippet is here as requested:
$startdate = "2015-02-03";
$enddate = "2015-02-05";
$sql = 'SELECT record_number, date, manmod, description, cal, serial, datein, dateout, retdate, refex, refexdate, sellersname, sellersaddress, buyersname, buyersaddress, rfddealer, del, warranty, months FROM record WHERE del="Live" AND date BETWEEN "$startdate" AND "$enddate" ORDER BY record_number DESC';
From the PHP website:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
In other words, since your query is in single quotes, the $startdate and $enddate variables are not interpreted as variables. The SQL query that is send to the database will literally contain $startdate and $enddate, and will therefore look something like this:
'SELECT column1, column2 FROM table WHERE date BETWEEN "$startdate" AND "$enddate" ORDER BY record_number DESC';
(I've simplified the query a bit for readability purposes)
Obviously, the database does not know how to interpret PHP variables, it will look for records with a date between those two strings, finds nothing and therefore returns 0 records.
In order to paste the contents of the variables in your SQL query, you will have to do one of two things:
Option 1: replace the single quotes with double quotes
If you choose this option, make sure that you either escape the existing double quotes, or change them into single quotes:
$sql = "SELECT column1, column2 FROM table WHERE date BETWEEN '$startdate' AND '$enddate' ORDER BY record_number DESC";
Option 2: concatenate the strings manually
You can also build op the query manually from multiple parts, and glue them together using PHP's concatenation operator, the dot (.).
$sql = 'SELECT column1, column2 FROM table WHERE date BETWEEN "' . $startdate . '" AND "' . $enddate;
You should convert it to a greater than and less than equation:
date > '$startdate' AND date < '$enddate'
The issue isn't with your SQL, but with your PHP.
You need to read up on how string concatenation works and how PHP treats strings that use ' and " differently when wrapped around strings.
$sql = 'SELECT * FROM record WHERE date BETWEEN "$startdate" AND "$enddate"';
Should be changed to one of the following:
$sql = 'SELECT * FROM record WHERE date BETWEEN "' . $startdate . '" AND "' . $enddate . '"';
OR:
$sql = "SELECT * FROM record WHERE date BETWEEN '$startdate' AND '$enddate'";
I've simplified the SQL to highlight the real issue at hand.

PHP MySQL Select * From Where Date < today

So I am building a function that prints out a league schedule. I've run into a little snag when trying to pull the last 5 matches. Here is my code:
$league ID, $direction and $limit are set by the functions parameters.
$matches = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'leagueDesigner_season_matches WHERE leagueID = ' . $leagueID . ' and date < CURRENT_DATE() ORDER BY date ' . $direction . ' LIMIT 0, ' . $limit);
Appologies, I forgot to finish the post. The code is returning all dates and not just the dates before today.
The most likely explanation for the behavior you observe is that the column named date is defined as a datatype other than DATE, DATETIME, or TIMESTAMP. (Likely, you've defined it as an integer or varchar), and MySQL is not doing a "date" comparison, it's comparing strings or integers.
But absent the definition of the date column, that's just conjecture.
If the "snag" you've hit is an error being returned from MySQL, my recommendation for debugging issues with SQL statements is to you build your SQL text into a string variable, as a separate step, and then echo (or printf or vardump) the contents of the variable containing the SQL text, before you try to execute it.
$sql = "SELECT foo FROM bar WHERE fee = " . $val . " ORDER BY foo DESC LIMIT 1 ";
echo $sql;
And verify that the string echoed out is the SQL text you intend to send to the database; taking that string and attempting to execute it through another MySQL client is an effective way of verifying the statement executes and returns the resultset you expect.
If you use any reserved words as column names, you may need to qualify those column names with a tablename, rowsource alias, etc., or enclose it in backticks. (EDIT: DATE is not a reserved word in MySQL 5.5)
... FROM mytable t WHERE t.date = ...
or
... FROM mytable t WHERE `date` = ...
Also note that including "unsafe" variables in SQL text can lead to SQL injection vulnerabilities.
For example,
$val = '1 OR 1=1';
$sql = "SELECT * FROM mytable WHERE id = ' . $val ;

MySQL Query Interpret Date String as Date

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

Getting mySQL date_format to display in PHP

This could sound like a very simple question to many of you, but I seem to be having trouble getting a basic date_format to work with my mySQL statement and then to be displayed using php. Here is the code that I currently have:
$result = mysql_query("SELECT *, DATE_FORMAT('timestamp', '%W %D %M %Y') as date FROM articleDB WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC LIMIT 8");
Then trying to display it using:
echo ' Posted: '.$row['timestamp'].'';
All I want is to format the date from a PHP myAdmin timestamp to the format I want.
Cheers
Use backticks ( `` ) or nothing at all instead of single-quotes ('`) around your field in your query:
$result = mysql_query("SELECT *, DATE_FORMAT(`timestamp`, '%W %D %M %Y') as date FROM articleDB WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC LIMIT 8");
Backticks ( `` ) creates a reference to a table member, single-quotes creates a string ('). You were basically trying toDATE_FORMATthe string'timestamp'` instead of the field.
Also, since you are using as to create a field alias, you want to refer to that field using the alias when outputting:
echo ' Posted: '.$row['date'];
you need to display the "date" column that you calculate/format in the select statement, the timestamp column contains the unformatted original date value.
echo ' Posted: '.$row['date'];
since in your SQL query you define the date formatting as date you access it by $row['date'].

Categories