How can PHP arrays and loops be utilized to generate dynamic SQL queries for search functions with multiple search fields?

When creating a search function with multiple search fields, PHP arrays can be used to store the search criteria entered by the user. By using loops, we can dynamically construct the SQL query based on the search criteria provided. This allows for a flexible and scalable solution that can handle various combinations of search fields.

// Sample PHP code snippet for generating dynamic SQL queries for search functions with multiple search fields

// Define an array to store the search criteria
$searchCriteria = array();

// Populate the array with search criteria based on user input
if (!empty($_POST['name'])) {
    $searchCriteria[] = "name = '" . $_POST['name'] . "'";
}
if (!empty($_POST['category'])) {
    $searchCriteria[] = "category = '" . $_POST['category'] . "'";
}
// Add more search criteria fields as needed

// Construct the SQL query based on the search criteria
$sql = "SELECT * FROM products";
if (!empty($searchCriteria)) {
    $sql .= " WHERE " . implode(" AND ", $searchCriteria);
}

// Execute the SQL query and fetch results
// $result = mysqli_query($connection, $sql);
// while ($row = mysqli_fetch_assoc($result)) {
//     // Process and display search results
// }