What are some best practices for creating a PHP and MySQL search feature with dropdown menus?
When creating a PHP and MySQL search feature with dropdown menus, it is important to sanitize user input to prevent SQL injection attacks. Use prepared statements to securely query the database based on the selected dropdown menu options. Additionally, consider implementing pagination to handle large result sets efficiently.
<?php
// Connect to MySQL 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, $_POST['search_term']);
$category = mysqli_real_escape_string($conn, $_POST['category']);
// Prepare SQL statement
$sql = "SELECT * FROM table WHERE category = ? AND column LIKE ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $category, $search_term);
// Execute query
$stmt->execute();
$result = $stmt->get_result();
// Display results
while ($row = $result->fetch_assoc()) {
echo $row['column'] . "<br>";
}
// Close connection
$stmt->close();
$conn->close();
?>
Keywords
Related Questions
- Are there any specific best practices or tips for beginners to keep in mind when starting to learn PHP programming?
- How can PHP and JavaScript be effectively used together to enhance user experience on a website?
- How can exceptions be effectively used in PHP classes to handle errors and communicate issues to the user?