How can one efficiently search and retrieve data from a database in PHP for content matching a specific query?
To efficiently search and retrieve data from a database in PHP for content matching a specific query, you can use SQL SELECT statements with prepared statements to prevent SQL injection attacks. You can also use LIKE or full-text search queries to search for partial matches or specific keywords in the database.
<?php
// Establish a connection 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);
}
// Prepare a SQL query to search for content matching a specific query
$search_query = "SELECT * FROM table_name WHERE column_name LIKE ?";
$stmt = $conn->prepare($search_query);
// Bind the parameter and execute the query
$search_term = "%specific_query%";
$stmt->bind_param("s", $search_term);
$stmt->execute();
// Retrieve the results
$result = $stmt->get_result();
// Loop through the results and output the data
while ($row = $result->fetch_assoc()) {
echo "Column Name: " . $row['column_name'] . "<br>";
}
// Close the connection
$stmt->close();
$conn->close();
?>