How can PHP be used to create a search feature for a news script that searches for all user-inputted terms in a database?
To create a search feature for a news script that searches for all user-inputted terms in a database, you can use PHP to retrieve the user input, construct a SQL query that searches for all the terms in the database, and display the results to the user.
<?php
// Retrieve user input from a form
$searchTerm = $_GET['search'];
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "news_database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Construct SQL query to search for all user-inputted terms in the database
$sql = "SELECT * FROM news WHERE title LIKE '%$searchTerm%' OR content LIKE '%$searchTerm%'";
$result = $conn->query($sql);
// Display search results to the user
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Title: " . $row["title"]. "<br>";
echo "Content: " . $row["content"]. "<br><br>";
}
} else {
echo "No results found.";
}
$conn->close();
?>
Related questions
-
T_OBJECT_OPERATOR PHP error
-
file paths special characters encoding
-
PHP form submission session management