您可以使用IN
运算符。
此外,请确保应用正确的转义(在这种情况下,这无关紧要,但在通过 Web 请求提交字段时会这样做):
$string = '3,4,5';
$array = explode(',', $string);
// cast all array elements into integers
$numbers = join(',', array_map('intval', $array));
$query = "SELECT ID FROM TABLE WHERE ID IN ($numbers)";
另一种奇特的方法是使用准备好的语句:
$placeholders = join(',', array_fill(0, count($array), '?'));
$query = "SELECT ID FROM TABLE WHERE ID IN ($placeholders)";
然后要执行查询,您将像这样绑定数字(PDO 示例):
// prepare the query, looks like 'WHERE ID IN (?,?,?)'
$stmt = $db->prepare($query);
// execute the query and pass the array values
$stmt->execute($array);