How can a PHP search form be implemented to search for specific content in a database?
To implement a PHP search form to search for specific content in a database, you can create a form that takes user input, then use PHP to query the database based on the input and display the results. This involves connecting to the database, constructing a SQL query with the search term, executing the query, and displaying the results in a user-friendly format.
<?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);
}
// Get search term from form
$searchTerm = $_POST['searchTerm'];
// Construct SQL query
$sql = "SELECT * FROM table_name WHERE column_name LIKE '%$searchTerm%'";
// 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 "0 results found";
}
// Close database connection
$conn->close();
?>