What are the best practices for implementing a search feature in PHP using SQL queries?
When implementing a search feature in PHP using SQL queries, it is important to sanitize user input to prevent SQL injection attacks. Additionally, using prepared statements can help improve performance and security by separating SQL logic from data. Finally, consider using full-text search capabilities in your database if you need to search through large amounts of text data efficiently.
// Sanitize user input
$searchTerm = mysqli_real_escape_string($conn, $_GET['search']);
// Prepare and execute SQL query
$stmt = $conn->prepare("SELECT * FROM products WHERE name LIKE ?");
$stmt->bind_param("s", $searchTerm);
$stmt->execute();
$result = $stmt->get_result();
// Display search results
while ($row = $result->fetch_assoc()) {
echo $row['name'] . "<br>";
}
Related Questions
- What are best practices for handling character encoding and decoding in PHP scripts, particularly when interacting with databases like MySQL?
- Are there any alternative functions or methods that can be used to achieve the same result as the provided PHP code?
- How should the pattern syntax be adjusted to handle domains with multiple dots, such as "www.zwei.punkte.de"?