How can PHP be used to prevent SQL injection vulnerabilities in a search function?
SQL injection vulnerabilities in a search function can be prevented by using prepared statements with parameterized queries in PHP. This approach helps to separate SQL code from user input, preventing malicious SQL queries from being executed.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Sanitize and validate user input
$searchTerm = htmlspecialchars($_GET['searchTerm']);
// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM products WHERE name LIKE :searchTerm");
$stmt->bindParam(':searchTerm', $searchTerm, PDO::PARAM_STR);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();