What potential pitfalls should be avoided when building a search field in PHP that interacts with a database?
One potential pitfall to avoid when building a search field in PHP that interacts with a database is SQL injection. To prevent SQL injection, it's important to use prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps sanitize user input and prevent malicious SQL code from being executed.
// Connect to database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Get user input from search field
$searchTerm = $_GET['search'];
// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE column_name LIKE :searchTerm");
// Bind the search term to the parameter
$stmt->bindParam(':searchTerm', $searchTerm, PDO::PARAM_STR);
// Execute the query
$stmt->execute();
// Fetch results
$results = $stmt->fetchAll();
// Display results
foreach ($results as $row) {
echo $row['column_name'] . "<br>";
}