我已经有几年没有编写PHP/SQL了,我需要为一个项目这样做。现在我遇到了一个问题。
我想在特定日期之间从MySQL数据库中抓取一些数据。如果像这样写它,它工作得很好:
$result = mysql_query("SELECT * FROM acw WHERE team = '".$team."' and added between '2012-11-05' and '2012-11-10' ");但我想从URL中获取日期,并编写了以下代码:
$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;如果我回显$period,我在超文本标记语言中得到了正确的输出,但是当我试图将它插入到我的MySQL问题中时,我什么也没有得到,我做错了什么?
$result = mysql_query("SELECT * FROM acw WHERE team = '".$team."' '".$period."' ");所以这出了点问题,我自己解决不了:
发布于 2012-11-11 04:13:30
$period中的字符串是一个完整的SQL块,而不是带引号的字符串文字。因此,删除它周围的单引号。
$result = mysql_query("SELECT * FROM acw WHERE team = '". $team ."' " . $period);
//---------------No quotes here----------------------------------------^^^^^^^^^^注意:我们假设如果$team源自用户输入,那么已经通过mysql_real_escape_string()对SQL注入进行了适当的转义。
建议总是通过echo输出字符串来调试您的SQL语句。
SELECT * FROM acw WHERE team = 'The Team' 'and added between '2012-11-05' and '2012-11-10''最后一句忠告-除非在这里没有发布的代码中已经完成了这项工作,否则在尝试使用$_GET['per']之前,请验证是否设置了它:
// 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;https://stackoverflow.com/questions/13325666
复制相似问题