为什么这个PDO查询不能正常工作?
$colors = $_GET['color'];
$colors = explode(' ', $colors);
$colors = implode(',',$colors);
$items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 IN (".$colors.")");
$items ->execute();
while($info = $items->fetch(PDO::FETCH_ASSOC))
{
echo $info['color_base1'];
}
您需要逃离$colors
,否则会受到SQL注入攻击。有一个鲜为人知的PHP函数array_fill
非常适合:
$colors = explode(' ', $_GET['color']));
$parameters = join(', ', array_fill(0, count($colors), '?');
$items = $con->prepare("SELECT * FROM item_descr WHERE color_base1 IN ({$parameters})");
$items ->execute($colors);
while($info = $items->fetch(PDO::FETCH_ASSOC)) {
echo $info['color_base1'];
}
你的问题似乎是你的颜色没有用引号括起来,但这个问题在我的代码中消失了,因为它使用了绑定参数。
如果处理字符串,则需要用引号转义$colors
项以适应IN()
语句:
SELECT * FROM item_descr WHERE color_base1 IN ('blue', 'yellow', '#FF0000')
您的$color
变量可能只是逗号分隔的-添加引号。
顺便说一句,要检查MySQL错误,请在运行查询后使用PDO::errorInfo:
var_dump($con -> errorInfo());
它将显示如下内容:
You have an error in your SQL syntax; [...]
这样您就可以修复您的查询。
如果$colors可以包含字符串,那么您应该使用
function quote_value(& $value, $key) { $value = "'$value'"; }
$colors = $_GET['color'];
$colors = explode(' ', $colors);
array_walk($colors, 'quote_value');
$colors = implode(',',$colors);
// the rest of your code