无论它们来自何处,都不应在查询中使用任何变量。PDO 和参数化查询的解决方案是将占位符添加到查询中。
我这样做是这样的:
function getPlaceholders ($array) {
return !empty($array)
? implode(',', array_fill(0, count($array), '?'))
: null;
}
$userIds = array(1,2,3,4);
$sql = 'SELECT FROM users WHERE id IN (' . $this->getPlaceholders($userIds) . ')';
$result = pdo_query($sql, $userIds);
通常,您会使用 OOP 格式。
$userIds = array(1,2,3,4);
$sql = 'SELECT FROM users WHERE id IN (' . $this->getPlaceholders($userIds) . ')';
$result = $this->db->query($sql, $userIds);
// common file which is extended
public function getPlaceholders ($array) {
return !empty($array)
? implode(',', array_fill(0, count($array), '?'))
: null;
}
这将生成如下查询:
SELECT FROM users WHERE id IN (?,?,?,?)