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 you ensure that data from one table is only displayed once in a multi-table query in PHP?
- Are there best practices for efficiently sorting multidimensional arrays in PHP to avoid performance issues?
- What are some alternative methods to array_push() for adding elements to associative arrays in PHP?