What are the potential pitfalls of using the LIKE operator in a MySQL query in PHP?
When using the LIKE operator in a MySQL query in PHP, one potential pitfall is the risk of SQL injection if user input is not properly sanitized. To prevent this, it is important to use prepared statements with parameterized queries to securely handle user input.
// Example of using prepared statements to securely handle user input with the LIKE operator
$searchTerm = $_POST['search_term'];
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
// Prepare a statement with a placeholder for the search term
$stmt = $pdo->prepare("SELECT * FROM table_name WHERE column_name LIKE :search_term");
// Bind the search term to the placeholder
$stmt->bindParam(':search_term', $searchTerm, PDO::PARAM_STR);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
// Loop through and display the results
foreach ($results as $result) {
echo $result['column_name'] . "<br>";
}