How to make a search for php

Create fast & accurate search results in PHP with an example - get the code & learn how to build a search engine.

Searching with PHP

Searching through a website's content can be accomplished using PHP. This tutorial will provide an overview of the search process and demonstrate an example of a simple search using PHP.

The first step in creating a search is to create a form that allows users to enter their search query. This form will typically contain an input field and a submit button, which will be used to submit the form. Here is an example of a simple search form:


<form action="search.php" method="post">
    <input type="text" name="query" />
    <input type="submit" value="Search" />
</form>

The form action should point to a file that will process the search query. When the form is submitted, the query will be sent as a POST variable called "query".

The next step is to create the search.php file that will process the search query. This file should start by retrieving the query from the POST variable. It should then use the query to search the database and return the results. Here is an example of how this can be done:


// Get the search query
$query = $_POST['query'];

// Connect to the database
$db = new PDO('mysql:host=localhost;dbname=database', 'user', 'password');

// Search the database
$stmt = $db->prepare('SELECT * FROM table WHERE field LIKE ?');
$stmt->execute(array('%'.$query.'%'));
$results = $stmt->fetchAll();

This code will search the database for any records that contain the search query in the specified field. The results can then be displayed to the user. Here is an example of how the results can be displayed in an HTML table:


// Display the results
echo '<table>';
foreach ($results as $row) {
    echo '<tr>';
    echo '<td>'.$row['field'].'</td>';
    echo '</tr>';
}
echo '</table>';

That's it! With these few lines of code, you can create a basic search using PHP. Of course, there are many other features that can be added to the search, such as pagination, sorting, and filtering.

Answers (0)