How can PHP be used to create a detailed search feature using MySQL database variables?
To create a detailed search feature using MySQL database variables in PHP, you can use a form to collect search criteria from users and then construct a SQL query based on the input. The SQL query can include various conditions using database variables to filter the results based on the user's search parameters.
<?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);
}
// Get search criteria from form
$search_term = $_POST['search_term'];
// Construct SQL query with database variables
$sql = "SELECT * FROM table_name WHERE column_name LIKE '%$search_term%'";
// Execute the query
$result = $conn->query($sql);
// Display search results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "No results found";
}
// Close database connection
$conn->close();
?>
Keywords
Related Questions
- How can prepared statements be used effectively in PHP to avoid inefficient queries within loops?
- What is the potential issue with the code that results in an "Array to String conversion" notice?
- How can the flush() function be strategically implemented in a PHP script to display real-time updates or progress messages to the user?