What are the best practices for constructing SQL queries in PHP to handle optional input fields like postal codes?

When constructing SQL queries in PHP to handle optional input fields like postal codes, it is important to dynamically build the query based on the presence of the input values. One approach is to use conditional statements to check if the input values are set, and then include them in the query accordingly. This ensures that the query is flexible and only includes the necessary conditions based on the provided input.

// Example code snippet for constructing SQL query with optional postal code input

// Initialize an empty array to store conditions
$conditions = [];

// Check if postal code input is set
if(isset($_POST['postal_code'])){
    // Add postal code condition to the array
    $conditions[] = "postal_code = '" . $_POST['postal_code'] . "'";
}

// Build the SQL query based on the conditions
$sql = "SELECT * FROM users";

if(!empty($conditions)){
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

// Execute the SQL query
$result = mysqli_query($connection, $sql);

// Process the query results
// ...