How can PHP developers effectively handle search queries in their code?
When handling search queries in PHP, developers can effectively sanitize user input to prevent SQL injection attacks and ensure the security of their application. One common approach is to use prepared statements with placeholders to separate SQL logic from user input, making it safer to execute queries.
// Example of handling a search query in PHP using prepared statements
// Assuming $searchTerm contains the user input for the search query
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare the SQL query with a placeholder for the search term
$stmt = $pdo->prepare("SELECT * FROM products WHERE name LIKE :searchTerm");
// Bind the search term to the placeholder
$stmt->bindParam(':searchTerm', $searchTerm, PDO::PARAM_STR);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
// Display or process the search results
foreach ($results as $result) {
echo $result['name'] . "<br>";
}