我正在尝试使用php和mysql构建查询,
$query = "select * from products where product_name = '$item_name'";
Run Code Online (Sandbox Code Playgroud)
当$ item_name只包含一个名称,但$ item_name是一个数组,并且基于用户的交互可以包含多个名称时,这是有效的,如何使查询运行多个名称并获取结果行.
提前致谢
以下是如何构建一个安全的名称列表以插入IN子句...
if (is_array($names) && count($names))
{
$filter="('".implode("','" array_map('mysql_real_escape_string', $names))."')";
$sql="select * from products where product_name in $filter";
//go fetch the results
}
else
{
//input was empty or not an array - you might want to throw an
//an error, or show 'no results'
}
Run Code Online (Sandbox Code Playgroud)
在通过mysql_real_escape_string运行每个名称以清理它之后,array_map返回名称的输入数组.我们内爆该数组以创建一个与IN子句一起使用的好列表.
您应该始终确保在查询中正确转义任何数据,特别是直接来自客户端的数据,以防止SQL注入攻击.
| 归档时间: |
|
| 查看次数: |
152 次 |
| 最近记录: |