How to make a search engine on php
Create your own search engine with PHP. Learn how with a step-by-step example.
Creating a Search Engine in PHP
Creating a search engine in PHP is actually quite straightforward. The following example will demonstrate a basic search engine using PHP and MySQL. This example will assume that you have a MySQL database set up, and that you have a table called ‘products’ containing the information you would like to be able to search.
Step 1: Create the HTML Form
The first step is to create the HTML form that will allow the user to input their search terms. This form will contain an input field for the search terms, and a submit button.
<form action="search.php" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
Step 2: Create the PHP Script
The next step is to create the PHP script that will process the search query. This script will receive the search query from the form, and will use it to generate a MySQL query that will search the database for the relevant results.
<?php
// Get the search query from the URL
$q = $_GET['q'];
// Connect to the database
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Create a MySQL query
$sql = "SELECT * FROM products WHERE title LIKE '%$q%'";
// Execute the query
$result = mysqli_query($con,$sql);
// Loop through the results and output each one
while($row = mysqli_fetch_array($result)) {
echo "<h2>".$row['title']."</h2>";
echo "<p>".$row['description']."</p>";
}
// Close the connection
mysqli_close($con);
?>
Step 3: Display the Results
The last step is to display the results. This can be done by looping through the results of the MySQL query, and displaying the relevant information.
while($row = mysqli_fetch_array($result)) {
echo "<h2>".$row['title']."</h2>";
echo "<p>".$row['description']."</p>";
}
And that's it! You now have a basic search engine that allows users to search your database for the relevant information.