2

我已经有几年没有写过 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;

如果我 echo $period 我在 HTML 中得到了正确的输出,但是当试图将它插入到我的 MySQL 问题中时,我什么也没得到,我做错了什么?

$result = mysql_query("SELECT * FROM acw WHERE team = '".$team."' '".$period."' ");

所以这有问题,我自己无法解决:(

4

1 回答 1

6

您输入的字符串$period是完整的 SQL 块,而不是带引号的字符串文字。所以删除它周围的单引号。

$result = mysql_query("SELECT * FROM acw WHERE team = '". $team ."' " . $period);
//---------------No quotes here----------------------------------------^^^^^^^^^^

注意:我们假设$team,如果源自用户输入,则已经通过 SQL 注入正确转义mysql_real_escape_string()

建议始终通过echo'ing out 字符串来调试您的 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;
于 2012-11-10T20:13:29.603 回答