What are the potential pitfalls of using nested IF operators in PHP for generating SQL queries?

Using nested IF operators for generating SQL queries can lead to messy and hard-to-read code, making it difficult to maintain and debug. It can also increase the chances of introducing syntax errors in the SQL query. To solve this issue, consider using a more organized and structured approach, such as building the SQL query dynamically based on user inputs using an array and then using functions like implode() to concatenate the query parts.

// Example of building a SQL query dynamically using an array
$conditions = [];

if ($condition1) {
    $conditions[] = "column1 = 'value1'";
}

if ($condition2) {
    $conditions[] = "column2 = 'value2'";
}

if ($condition3) {
    $conditions[] = "column3 = 'value3'";
}

// Construct the SQL query
$sql = "SELECT * FROM table_name";
if (!empty($conditions)) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

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