PHP implode in bind_param

I’m trying to create an advanced search in php. The inputs are not required, users can decide if they want to search for a manufacturer or just set the minimum price, etc. I’m trying to save the “s” and “i” for the bind_param in an array, and the variables in another array, then implode them in the bind_param part. This is where I got the problem. The $params implode works fine, but when I’m trying to implode the $vars array, I get the error message that says “Only variables should be passed by reference”. It’s because if I push a variable to my array, it stores it’s value and not the variable itself. I’ve tried to push them as strings, like ‘$example’, but in this case, when I implode it, got the same message because it’s a string. So, how should I store them in the array to be able to use them in the bind_param?

In this example I show only 2 inputs, but ofc I have a lot more.

if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['search_button'])) {
    $params[] = "i";
    $vars[] = '$status';
    $sql_search = 'SELECT m.*, u.premium, u.avatar FROM motorcycles m INNER JOIN users u ON u.id = m.userid WHERE status = ?';

    if (isset($_GET['manufacturer_search']) && $_GET['manufacturer_search'] !== "") {
        $manufacturer_search = $_GET['manufacturer_search'];
        $sql_search .= " AND manufacturer LIKE ?";
        array_push($params, 's');
        array_push($vars, '$manufacturer_search');
    }

    if (isset($_GET['min_price']) && $_GET['min_price'] !== "") {
        $min_price = $_GET['min_price'];
        $sql_search .= " AND price >= ?";
        array_push($params, 'i');
        array_push($vars, '$min_price');
    }

    $sql_search .= " ORDER BY u.premium DESC LIMIT ?, ?";
    array_push($params, 'ii');
    array_push($vars, '$this_page_first_result', '$results_per_page');


    $stmt_search = $link->prepare($sql_search);
    $stmt_search->bind_param(implode("", $params), implode(",", $vars));
    $stmt_search->execute();
    $result = $stmt_search->get_result();
}

Answer

You should provide the variables you want separately as the last parameter of bind_params, what you are doing is creating a string of all your variables and passing that.

Change

$stmt_search->bind_param(implode("", $params), implode(",", $vars));

To

$stmt_search->bind_param(implode("", $params), ...$vars );

And PHP will take all entries inside your $vars array and pass them as separate parameters of the function.

For more information on this see the Documentation of bind_param, PHP’s introduction of the splat operator here and here and some extra information on stack overflow.