Are there any common pitfalls to avoid when creating a search function in PHP for a client's website?
One common pitfall to avoid when creating a search function in PHP for a client's website is not properly sanitizing user input, which can leave the website vulnerable to SQL injection attacks. To prevent this, always use prepared statements to interact with the database when executing search queries.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
// Sanitize user input
$searchTerm = $_GET['searchTerm'];
$searchTerm = htmlspecialchars($searchTerm);
$searchTerm = $pdo->quote($searchTerm);
// Prepare and execute the search query
$stmt = $pdo->prepare("SELECT * FROM table_name WHERE column_name LIKE :searchTerm");
$stmt->execute(array(':searchTerm' => "%$searchTerm%"));
// Fetch and display search results
$results = $stmt->fetchAll();
foreach ($results as $result) {
echo $result['column_name'] . "<br>";
}