我几年没有编写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,我在HTML中得到了正确的输出但是当我试图将它插入我的MySQL问题时我什么都没有,我做错了什么?
$result = mysql_query("SELECT * FROM acw WHERE team = '".$team."' '".$period."' ");
这样做有些不对劲,我自己无法解决:(
答案 0 :(得分:6)
$period
中的字符串是一大块SQL,而不是带引号的字符串文字。所以删除它周围的单引号。
$result = mysql_query("SELECT * FROM acw WHERE team = '". $team ."' " . $period);
//---------------No quotes here----------------------------------------^^^^^^^^^^
注意:我们假设$team
(如果来自用户输入)已经通过mysql_real_escape_string()
建议始终通过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;