I haven't been writing PHP/SQL in a few years and needed to do this for a project. And now I have run into a problem.
I wanting to grab some data from a MySQL databas, between specific dates. It works just fine if write it like this:
$result = mysql_query("SELECT * FROM acw WHERE team = '".$team."' and added between '2012-11-05' and '2012-11-10' ");
But I want to get the dates from the URL, and have written this:
$periods = $_GET["per"];
if ( $periods == 1 ) {
$period = "and added between '2012-11-05' and '2012-11-10'";
}
elseif ( $periods == 2 ) {
$period = "and added between '2012-11-11' and '2012-11-17'";
}
elseif ( $periods == 3 ) {
$period = "and added between '2012-11-05' and '2012-11-10'";
}
echo $period;
If I echo $period I got the correct output in the HTML but when trying to insert it to my MySQL questions i got nothing, what does I do wrong?
$result = mysql_query("SELECT * FROM acw WHERE team = '".$team."' '".$period."' ");
So something is wrong with this, and can't solve it by my self :(
Your string in $period
is a full chunk of SQL, not a quoted string literal. So remove the single quotes surrounding it.
$result = mysql_query("SELECT * FROM acw WHERE team = '". $team ."' " . $period);
//---------------No quotes here----------------------------------------^^^^^^^^^^
Note: We assume that $team
, if originating from user input, has already been properly escaped against SQL injection via mysql_real_escape_string()
It is recommended to always debug your SQL statement by echo
'ing out the string. It would have been a little more obvious to see a string like:
SELECT * FROM acw WHERE team = 'The Team' 'and added between '2012-11-05' and '2012-11-10''
A final word of advice - unless this is already done in code not posted here, verify that $_GET['per']
is set before attempting to use it:
// Set $periods to the $_GET value or defualt to 1 if it isn't set (or whatever value)
$periods = isset($_GET["per"]) ? $_GET['per'] : 1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.