Search code examples
phpmysqlarraysmysqlibindparam

Solution to bind 2+ arrays as params in MySQL prepared statement?


I was able to bind 1 array as a parameter no problem. However, I am trying to bind 2+ arrays as parameters and its not going over so well. I keep getting an error that I cannot use positional arguments after unpacking. How do I combine the arrays as parameters?

$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);

Solution

  • You will have to combine the two lists together and then bind them in one go...

    $params = array_merge($_POST['category'],$_POST['location']);
    $stmt->bind_param(str_repeat('s', count($params)), ...$params);