Create a dynamic mysql query using php variables

Just check if the variables contain a value and if they do, build the query like so:

$sql = [];
$parameters = [];
    
if ($stationFilter) {
    $sql[] = " STATION_NETWORK = ?";
    $parameters[] = $stationFilter;
}
if ($verticalFilter) {
    $sql[] = " VERTICAL = ?";
    $parameters[] = $verticalFilter;
}

$query = "SELECT * FROM tableName";

if ($sql) {
    $query .= ' WHERE ' . implode(' AND ', $sql);
}
$stmt = $mysqli->prepare($query);

if ($parameters) {
    $stmt->bind_param(str_repeat('s', count($array), ...$parameters);
}
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);

Leave a Comment