What are some best practices for creating a search form in PHP that retrieves results from a database?
When creating a search form in PHP that retrieves results from a database, it is important to sanitize user input to prevent SQL injection attacks. Additionally, using prepared statements can help protect against SQL injection and improve performance. Lastly, consider implementing pagination to display search results in a user-friendly manner.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sanitize user input
$search_term = mysqli_real_escape_string($conn, $_GET['search']);
// Prepare and execute query
$stmt = $conn->prepare("SELECT * FROM table WHERE column LIKE ?");
$stmt->bind_param("s", $search_term);
$stmt->execute();
$result = $stmt->get_result();
// Display search results
while ($row = $result->fetch_assoc()) {
echo $row['column_name'] . "<br>";
}
// Close connection
$stmt->close();
$conn->close();
?>
Related Questions
- What are best practices for concatenating strings in PHP to create file paths?
- What are some resources or tutorials that provide clear explanations and examples of using conditional statements in regular expressions with PHP?
- Are there any specific guidelines or recommendations for handling data output from a database in PHP to ensure compatibility with different browsers and operating systems?