How can the LIKE operator be correctly implemented in PHP when querying a MySQL database?
When using the LIKE operator in PHP to query a MySQL database, you need to properly format the query string with the % wildcard characters before and after the search term. This allows for partial matching of strings in the database. Make sure to sanitize user input to prevent SQL injection attacks.
// Assuming $searchTerm contains the user input to search for
$searchTerm = $_POST['search_term']; // Example user input
// Sanitize the input
$searchTerm = mysqli_real_escape_string($conn, $searchTerm);
// Query to search for a specific term in a column using the LIKE operator
$query = "SELECT * FROM table_name WHERE column_name LIKE '%".$searchTerm."%'";
// Execute the query and fetch results
$result = mysqli_query($conn, $query);
Keywords
Related Questions
- How can developers ensure the security and integrity of their PHP applications when migrating to PHP 7.0 and implementing PDO for database access?
- What is the purpose of comparing and copying PHP files in different directories?
- How can the use of backticks and reserved names impact the functionality of queries in PHP when using MySQL?