Variable number of parameters on a prepared statement in PHP

Sometimes, you need to use a different number of parameters for a prepared statement. The call_user_func_array function allows you to call bind_param with a varying number of parameters.



// Start by validating your data
$something = filter_input(INPUT_POST, 'something', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^(this|that|other|thing)$/i']]);

// Set up the types string
$types = '';

// Initialize the array the variables will be referenced from
$values = [];

// Create the base SQL statement
$query = 'SELECT * FROM table';

// Initialize an array to store the WHERE comparisons
$where = [];

// Check to see if $something should be used 
// empty tests for both null (no data in input) and false (invalid data)
if (!empty($something)) {
   
    // Set the WHERE comparison for something
    $where[] = 'something = ?';

    // Append the type for this comparison
    $types .= 's';

    // Add a reference to the $something variable (that's what the ampersand is)
    $values[] = &$something;

}

// If the $where array has elements, add them to the query
if (count($where) > 0) {
    $query .= ' WHERE '.implode(' AND ',$where);
}

$stmt = $mysqli->prepare($query);

// Create the array of parameters which will be sent to the bind_param method
$params = array_merge([$types],$values);

// Bind the variables
call_user_func_array([$stmt,'bind_param'],$params);