在 MySQL 准备好的语句中将 2+ 个数组绑定为参数的解决方案?
Solution to bind 2+ arrays as params in MySQL prepared statement?
我能够绑定 1 个数组作为参数没问题。但是,我正在尝试将 2+ 个数组绑定为参数,但效果不是很好。解包后我不断收到无法使用位置参数的错误。如何组合数组作为参数?
$query="SELECT price FROM products WHERE status='1'";
if(isset($_POST['category'])){
$category_filter = join(',', array_fill(0, count($_POST['category']), '?'));
$sql .= ' AND category IN ('.$category_filter.')';
}if(isset($_POST['location'])){
$location_filter = join(',', array_fill(0, count($_POST['location']), '?'));
$sql .= ' AND location IN ('.$location_filter.')';
}
$stmt = $conn->prepare($query);
$stmt->bind_param(str_repeat('ss', count($_POST['category'],$_POST['location'])), ...$_POST['category'],...$_POST['location']);
$stmt->execute();
$stmt->bind_result($price);
您必须将两个列表合并在一起,然后将它们一次性绑定...
$params = array_merge($_POST['category'],$_POST['location']);
$stmt->bind_param(str_repeat('s', count($params)), ...$params);
我能够绑定 1 个数组作为参数没问题。但是,我正在尝试将 2+ 个数组绑定为参数,但效果不是很好。解包后我不断收到无法使用位置参数的错误。如何组合数组作为参数?
$query="SELECT price FROM products WHERE status='1'";
if(isset($_POST['category'])){
$category_filter = join(',', array_fill(0, count($_POST['category']), '?'));
$sql .= ' AND category IN ('.$category_filter.')';
}if(isset($_POST['location'])){
$location_filter = join(',', array_fill(0, count($_POST['location']), '?'));
$sql .= ' AND location IN ('.$location_filter.')';
}
$stmt = $conn->prepare($query);
$stmt->bind_param(str_repeat('ss', count($_POST['category'],$_POST['location'])), ...$_POST['category'],...$_POST['location']);
$stmt->execute();
$stmt->bind_result($price);
您必须将两个列表合并在一起,然后将它们一次性绑定...
$params = array_merge($_POST['category'],$_POST['location']);
$stmt->bind_param(str_repeat('s', count($params)), ...$params);