How can PHP be used to search for specific keywords in MySQL table fields?
To search for specific keywords in MySQL table fields using PHP, you can use the SQL SELECT statement with the LIKE clause. This allows you to search for a specific keyword within a field by using wildcard characters. You can then execute the query using PHP's mysqli or PDO extension to interact with the MySQL database.
<?php
// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Define the keyword to search for
$keyword = "example";
// Prepare the SQL query to search for the keyword in a specific table field
$query = "SELECT * FROM table_name WHERE field_name LIKE '%".$keyword."%'";
// Execute the query
$result = $mysqli->query($query);
// Fetch and display the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "No results found.";
}
// Close the connection
$mysqli->close();
?>
Related questions
-
PHP date functions database query
-
PHP forums documentation official resources
-
PHP nested loops database