How can the PHP code be optimized to handle multiple search criteria entered by the user in a form, targeting specific database columns for each search term?

To optimize the PHP code for handling multiple search criteria entered by the user in a form targeting specific database columns for each search term, you can dynamically construct the SQL query based on the user's input. This can be achieved by building the WHERE clause of the query dynamically, adding conditions for each search term and database column specified by the user.

<?php
// Assuming form inputs are submitted via POST method
$searchTerm1 = $_POST['searchTerm1'];
$searchTerm2 = $_POST['searchTerm2'];
$searchColumn1 = $_POST['searchColumn1'];
$searchColumn2 = $_POST['searchColumn2'];

// Establish a database connection
$connection = new mysqli("localhost", "username", "password", "database");

// Construct the SQL query dynamically based on user input
$sql = "SELECT * FROM your_table WHERE 1=1";

if (!empty($searchTerm1) && !empty($searchColumn1)) {
    $sql .= " AND $searchColumn1 LIKE '%$searchTerm1%'";
}

if (!empty($searchTerm2) && !empty($searchColumn2)) {
    $sql .= " AND $searchColumn2 LIKE '%$searchTerm2%'";
}

// Execute the query
$result = $connection->query($sql);

// Process the results
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Output or process the data as needed
    }
} else {
    echo "No results found.";
}

// Close the database connection
$connection->close();
?>