How can SQL queries be optimized when retrieving specific data based on user input in PHP?

When retrieving specific data based on user input in PHP, SQL queries can be optimized by using prepared statements to prevent SQL injection attacks and improve performance. By binding user input parameters to the query, the database can efficiently execute the query without the need for constant parsing. Additionally, using indexes on columns frequently used in WHERE clauses can further optimize query performance.

// Assuming $userInput is the user input for filtering data
$userInput = $_POST['user_input'];

// Prepare a SQL query with a parameterized statement
$stmt = $pdo->prepare("SELECT * FROM table_name WHERE column_name = :user_input");

// Bind the user input parameter to the query
$stmt->bindParam(':user_input', $userInput);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Process the results as needed
foreach ($results as $row) {
    // Do something with the data
}