What are some best practices for implementing a search function in PHP that searches through a database table with keywords?
Implementing a search function in PHP that searches through a database table with keywords involves creating a SQL query that uses the LIKE operator to match the keywords against the columns in the table. It is important to properly sanitize the input to prevent SQL injection attacks and to handle any potential errors gracefully.
<?php
// Get the search keyword from the user input
$searchKeyword = $_GET['keyword'];
// Sanitize the input to prevent SQL injection
$searchKeyword = mysqli_real_escape_string($conn, $searchKeyword);
// Execute a SQL query to search for the keyword in the database table
$query = "SELECT * FROM table_name WHERE column_name LIKE '%".$searchKeyword."%'";
$result = mysqli_query($conn, $query);
// Check if any results were found
if(mysqli_num_rows($result) > 0) {
// Display the search results
while($row = mysqli_fetch_assoc($result)) {
echo $row['column_name'] . "<br>";
}
} else {
echo "No results found";
}
// Close the database connection
mysqli_close($conn);
?>
Related Questions
- Are there any PHP frameworks like Adventure PHP Framework, Zend, or CakePHP that support ORM functionality?
- Welche Vor- und Nachteile haben die vorgeschlagenen Lösungen, wie die Umgestaltung des Forum-Templates oder die Verwendung von <iframe>?
- How can the regex pattern in preg_match be modified to only allow specific characters in a string?