How does using a database in PHP improve search functionality and data retrieval compared to text files?
Using a database in PHP improves search functionality and data retrieval compared to text files because databases allow for faster and more efficient querying of data using SQL. Databases also provide features such as indexing, which speeds up search operations, and the ability to store and retrieve structured data in a more organized manner.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Perform a search query
$search_term = "example";
$sql = "SELECT * FROM myTable WHERE column LIKE '%$search_term%'";
$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 the database connection
$conn->close();