What are some best practices for implementing a search function on a website using PHP?
Implementing a search function on a website using PHP involves creating a form for users to input their search query, processing the input on the server side, querying the database for relevant results, and displaying the results to the user.
<?php
// Connect 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);
}
// Process search query
if(isset($_GET['search'])) {
$search = $_GET['search'];
// Query the database for relevant results
$sql = "SELECT * FROM table WHERE column LIKE '%$search%'";
$result = $conn->query($sql);
// Display search results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Result: " . $row["column"] . "<br>";
}
} else {
echo "No results found.";
}
}
$conn->close();
?>
Related Questions
- In PHP, what are the best practices for allowing users to modify pages in a CMS - online via a <textarea> element, through a PHP editor, or using a standard text editor like Notepad?
- What are the alternatives to creating thumbnails in PHP and saving them, considering potential limitations with image formats like GIF?
- What are common challenges faced when creating a private messaging system in PHP?