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.
Related
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 ;
I have a mysql datetime field that stores dates in the form '2013-12-25 00:00:00'
I need to select all records for any month in the table with a query like:
$sql = "SELECT *
FROM `images`
WHERE (photodate BETWEEN '2003-11-01 00:00:00' AND '2003-12-03 00:00:00')
ORDER BY photodate DESC
LIMIT 30";
The above select query does the job fine.
In order to change the dates, I need to replace the '2003-11-01 00:00:00'AND'2003-12-03 00:00:00' with variables, so I set a variable with input data from two drop down lists for $startyear and $startmonth and convert it to what I think is the correct form using:
$startdate = $startyear."-".$startmonth."-01 00:00:00";
I do the same to the $enddate by adding 1 to the $startmonth.
My code then becomes:
$sql = "SELECT *
FROM `images`
WHERE (photodate BETWEEN $startdate AND $enddate)
ORDER BY photodate DESC
LIMIT 30";
This does not work at all and gives a MySQL error. Having struggled with it for a month and finding nothing on any forum that uses variables instead of text, I am totally at a loss as to how it could be done. All help appreciated.
You are vulnerable to SQL injection attacks, which is why it's not working. You're producing the literal query
... WHERE (photodate BETWEEN 2003-11-01 00:00:00 AND 2013-12-03 00:00:00)
The 2003-11-01 and 2013-12-03 will be interpreted as a series of mathematical subtractions, and the 00:00:00 will be a simple flat-out syntax error. You need to, at bare minimum, quote those values:
... WHERE (photodate BETWEEN '$startdate' AND '$enddate')
^----------^-----^--------^--- note the quotes
so that mysql can see the WHOLE date as a date value, and not some arbitrary broken strings.
I guess you're missing some apostrophes... try this:
$sql = "SELECT * FROM images WHERE (photodate BETWEEN '$startdate' AND '$enddate') ORDER BY photodate DESC LIMIT 30";
You could have problems with the logic. In $enddate doesn't adding 1 to the start month give you 13?
Try printing out the contents $sql when the variables are in and see how it compares to the working $sql.
Please add apostrophes your query (and sanitize your variables using mysql_real_escape_string, PDO bind values, mysqli_real_escape_string) :
$sql = 'SELECT * FROM 'images' WHERE (photodate BETWEEN '.$startdate.' AND '.$enddate.') ORDER BY photodate DESC LIMIT 30';
A little reminder, you shall NOT use MySQL (deprecated, old.. and not that fast), if you're using MySQLi or going to use it, please sanitize your variables like this, as Marc B said it could break your script and your app security :
<?php
// Starting MySQLi Connection
$db = mysqli_connect("host", "user", "password", "dbname");
// Sanitizing your variables
$startdate = mysqli_real_escape_string($db, $startdate);
$enddate = mysqli_real_escape_string($db, $enddate);
// Query
$sql = "SELECT * FROM 'images' WHERE (photodate BETWEEN ".$startdate." AND ".$enddate.") ORDER BY photodate DESC LIMIT 30";
// Doing the query and print the result array
$var = mysqli_query($db, $sql);
print_r($var);
// Closing connection
mysqli_close($db);
?>
Please refer to to this for PDO way or to this for MySQLi way, you can also check the MySQL_real_escape_string into PHP doc but MySQL functions are deprecated since PHP 5.5
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 . '"');
^-- ^--
My Sql Query Returning Empty results set. Is there any Mistake in format. I am Using some php variables inside the query..
public function getBlockDate($month,$year){
$connection = db::factory('mysql');
$time_from="00-00-00";
$time_to="23-59-59";
$sql = 'select * from blocks WHERE date LIKE "'.$year.'-'.$month.'%" AND (time_From="'.$time_from.'" AND time_to="'.$time_to.'")';
return $connection->getArray($sql);
}
*Here time_from and time_to table columns are of time type*
Change your SQL query
$sql = 'select * from blocks WHERE date LIKE "'.$year.'-'.$month.'%" AND (time_From="'.$time_from.'" AND time_to="'.$time_to.'")';
' single quotes are missing over $time_from and $time_to
EDITED QUERY
$time_from="00:00:00";
$time_to="23:59:59";
$sql = 'select * from blocks WHERE date LIKE "'.$year.'-'.$month.'%" BETWEEN (time_From="'.$time_from.'" AND time_to="'.$time_to.'")';
also change the - with : in your $time_from and $time_to variables
This should work for you. You didn't put quotas right at the AND clause.
Also when using LIKE in your query be sure to place the wildcard correctly. In your case you are looking for records in date column whose start with year-month then there's your time.
$time_from="00-00-00";
$time_to="23-59-59";
$sql = "SELECT * FROM blocks WHERE date LIKE '".$year."-".$month."%' AND (time_From='".$time_from."' AND time_to='".$time_to."')";
Convert date and time to universal format and then query using it.
I need to match the result format of 2 code:
I need to get the output/format of this:
$event_day = $year.'-'.$month.'-'.$list_day; // $event_day
match this:
DATE_FORMAT(date,'%Y-%m-%d')
Full code:
$query = "
SELECT title, DATE_FORMAT(date,'%Y-%m-%d') AS date
FROM table
WHERE user_id = '$session_user_id'
AND date BETWEEN '$year-$month-1' AND '" . date("Y-m-t", strtotime("$year-$month-1")) . "'
AND active = 1";
My problem is that $event_day is only displaying events for: October, November and December.
I had a similar problem with this code below:
$query = "
SELECT title, DATE_FORMAT(date,'%Y-%m-%d') AS date
FROM table
WHERE user_id = '$session_user_id'
AND date LIKE '$year-$month%'
AND active = 1";
and it was fixed with this code:
$query = "
SELECT title, DATE_FORMAT(date,'%Y-%m-%d') AS date
FROM table
WHERE user_id = '$session_user_id'
AND date BETWEEN '$year-$month-1' AND '" . date("Y-m-t", strtotime("$year-$month-1")) . "'
AND active = 1";
Anyone know how I could sort this out?
If you are simply trying to match dates in a SQL query, which is what you look like you're after, you can just pass the date as a string with a # on each end. This will tell SQL to parse the string as a date and the format you give it in is not really important. The exception to this is it can get confused between US/EU date formats like dd/mm/yyyy vs mm/dd/yyyy.
$query = "SELECT title, DATE_FORMAT(myDate,'%Y-%m-%d') AS formattedDate
FROM table
WHERE user_id = '$session_user_id'
AND (myDate BETWEEN #$year-$month-1# AND #$year-$month-1#)
AND active = 1";
This format should work but your query is select records that fall between the same date so you'll only get records that are actually on that date. You might as well just use WHERE date = #$year-$month-1#
edit: this assumes your date field datatype is correctly set up in the database as a date/time.
edit2: "date" is often a reserved word in databases and shouldn't really be used for field names and variables. See edited code above.
In addition I would suggest using php to format the date using the date() function rather than format it in the query. This allows more flexibility to actually use the date in your script.