How can PHP be used to query a database for entries related to a specific keyword, regardless of its position within the data?
When querying a database for entries related to a specific keyword, regardless of its position within the data, you can use the SQL LIKE operator in combination with PHP. This allows you to search for a keyword within a database column without specifying its exact position. By using the '%' wildcard character before and after the keyword, you can retrieve all entries that contain the keyword anywhere in the data.
<?php
// Connect to 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);
}
// Keyword to search for
$keyword = "example";
// SQL query to retrieve entries related to the keyword
$sql = "SELECT * FROM table_name WHERE column_name LIKE '%".$keyword."%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results found";
}
$conn->close();
?>