What are some common pitfalls when using LIKE queries in PHP to search for multiple criteria in a database?
One common pitfall when using LIKE queries in PHP to search for multiple criteria in a database is not properly escaping user input, which can lead to SQL injection attacks. To solve this issue, you should always use prepared statements with placeholders to safely pass user input to the query.
// Example of using prepared statements with placeholders to search for multiple criteria in a database
// User input
$searchTerm1 = $_POST['searchTerm1'];
$searchTerm2 = $_POST['searchTerm2'];
// Database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare the SQL query
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE column1 LIKE :searchTerm1 AND column2 LIKE :searchTerm2");
// Bind the search terms to placeholders
$stmt->bindParam(':searchTerm1', $searchTerm1);
$stmt->bindParam(':searchTerm2', $searchTerm2);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Display the results
foreach ($results as $row) {
echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}
Keywords
Related Questions
- What are the drawbacks of using $PHP_SELF instead of $_SERVER['PHP_SELF'] in form action attributes in PHP scripts?
- What are some potential pitfalls to be aware of when using PHP scripts for email subscription management?
- How can PHP scripts be structured to handle multiple form submissions on the same page without conflicts?