How can PHP variables be properly utilized in a search function to ensure accurate results?
When using PHP variables in a search function, it is important to properly sanitize and validate user input to prevent SQL injection attacks and ensure accurate results. One way to achieve this is by using prepared statements with placeholders in your SQL query to bind the user input securely.
// Assume $searchTerm is the user input from a search form
$searchTerm = $_GET['searchTerm'];
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with a placeholder
$stmt = $pdo->prepare("SELECT * FROM products WHERE name LIKE :searchTerm");
// Bind the sanitized search term to the placeholder
$stmt->bindParam(':searchTerm', $searchTerm, PDO::PARAM_STR);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();