1. HTML (Search Box Form)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Search Box Example</title> </head> <body> <!-- Search Form --> <form action="search.php" method="GET"> <input type="text" name="query" placeholder="Search..." required> <button type="submit">Search</button> </form> </body> </html> |
PHP (search.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<?php // Database connection (update with your database credentials) $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // replace with your database name // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if (isset($_GET['query'])) { // Get the search query from the URL $query = mysqli_real_escape_string($conn, $_GET['query']); // SQL query to search for the entered term in a specific column (e.g., 'title' or 'content') $sql = "SELECT * FROM your_table_name WHERE title LIKE '%$query%' OR content LIKE '%$query%'"; // Execute the query $result = $conn->query($sql); if ($result->num_rows > 0) { // Display results echo "<h2>Search Results:</h2>"; while($row = $result->fetch_assoc()) { echo "<div>"; echo "<h3>" . $row['title'] . "</h3>"; echo "<p>" . $row['content'] . "</p>"; echo "</div><hr>"; } } else { echo "No results found for '$query'."; } } // Close the connection $conn->close(); ?> |