In this article, we’re going to search for a string in our database and then display the search result using php and MySQL. I’ll like to see this as a minor search engine which works for a single website. Let’s start with creating our mySQL database.
Note: you should have a basic knowledge of php and MySQL in order to follow up this article.
Creating your database.
Using your phpmyadmin tool in XAMPP let’s create our database named “Charmingdesk” with a table named “my_blog”.
In creating our table, we give the table columns like “id”, “post-title”, “post-body”, and “author”. Let’s use this four columns to make our search simple. Now we insert values to the rows which we are going to work with. We’ll use the insert tool in phpmyadmin to achieve this.
In the first row.
In the second row.
Let’s work with just these two rows, you can add as many rows as you like to test out this search algorithm. Now we’re done with our database, lets create our index.php file and connect to it.
Connecting your index.php file to the database.
First we’ll create a new file and name it index.php then in that file we use the mysqli_connect function to connect to our SQL database.
"localhost", "root", "", "Charmingdesk"
//Hostname, username, password and database name respectively.
Now that we’ve connected our script, let’s create our search bar using HTML and a button to trigger our search. Remember, We’re still working with our index.php file.
name="mysearch" placeholder="search for articles">
Now we begin writing our php script to trigger the search
//Now let's select all the items in our database.
mysqli_query($con,"select * from my_blog ");
echo "results found";
Let’s explain this code a little. We first selected all the all the articles in the database and arranged them in an array. Now we want to search for a title matching the one written in our html search input. To do that, we loop through all the iterables in our array finding a match between our html input value and one of the titles in our database. If a match is found, it displays the title, body and author of that post on the screen and continues that way till all the matches have been displayed.
Note: the stripos function is case insensitive. If you want a case sensitive search, use the strpos function.
Now we’ve been able to perform our own database search with php. Feel free to leave us a comment below, we’ll love to know what you think about this article. You can also follow is on social media using the buttons below.
Or send us an email at email@example.com for a private reply. Kudo’s on your web development journey.