How can PHP be used to efficiently search through a MySQL database for specific content?
To efficiently search through a MySQL database for specific content using PHP, you can use the SELECT statement with a WHERE clause to filter the results based on the search criteria. You can also use prepared statements to prevent SQL injection attacks and improve performance.
<?php
// Establish a connection to the 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);
}
// Search query
$search_term = "keyword";
$stmt = $conn->prepare("SELECT * FROM table_name WHERE column_name LIKE ?");
$search_param = "%{$search_term}%";
$stmt->bind_param("s", $search_param);
$stmt->execute();
$result = $stmt->get_result();
// Output results
while ($row = $result->fetch_assoc()) {
echo "Found: " . $row['column_name'] . "<br>";
}
// Close connection
$stmt->close();
$conn->close();
?>