Creating a Search Filter Function using PHP/PDO

In this tutorial we will create a Search Filter using PHP/PDO. This code can search data in the database server with the use of a PDO query when the user enters the keyword value in the form. The code uses a PDO query to search and locate a specific data in the table row by adding a WHERE Clause and Like Operator to the query in order to display the list of data that based on the given keyword.

We will be using PDO as a query scripting it an acronym for PHP Data Objects. It is a lean, clean, and consistent way to access databases. This means developers can write portable code much easier.

Getting Started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html.

And, this is the link for the bootstrap that I used for the layout design https://getbootstrap.com/.

Before we proceed to the creation of the web application, we will start our web-server and database first. To do this, open the XAMPP's Control Panel and start the "Apache" and "MySQL".

Creating Database

Open your database web server (PHPMyAdmin [http://localhost/phpmyadmin]) then create a database naming "db_pdo_search", after that click "Import" then locate the database file inside the extracted folder of the application then click the "Go" button.

tut1

You can also create our sample table programmatically. To do this, after creating a new databse, click the "SQL" Menu at the menu bar then copy the code below and paste into the textarea provided.

  1. CREATE TABLE `member` (
  2. `firstname` varchar(50) NOT NULL,
  3. `lastname` varchar(50) NOT NULL,
  4. `address` varchar(100) NOT NULL
  5.  
  6.  
  7. INSERT INTO `member` (`mem_id`, `firstname`, `lastname`, `address`) VALUES
  8. (1, 'John', 'Smith', 'New York'),
  9. (2, 'Claire', 'Temple', 'Racoon City');

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy and paste the code below then save the file as "conn.php".

  1. <?php
  2. $conn = new PDO( 'mysql:host=localhost;dbname=db_pdo_search', 'root', '');
  3. if(!$conn){
  4. die("Error: Failed to coonect to database!");
  5. }
  6. ?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as "index.php".

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
  5. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  6. </head>
  7. <body>
  8. <nav class="navbar navbar-default">
  9. <div class="container-fluid">
  10. <a href="https://www.sourcecodester.com" class="navbar-brand">Sourcecodester</a>
  11. </div>
  12. </nav>
  13. <div class="col-md-3"></div>
  14. <div class="col-md-6 well">
  15. <h3 class="text-primary">PHP - Search Filter Using PDO</h3>
  16. <hr style="border-top:1px dotted #ccc;" />
  17. <div class="col-md-4">
  18. <form method="POST" action="insert.php">
  19. <div class="form-group">
  20. <label>Firstname</label>
  21. <input type="text" name="firstname" class="form-control" required="required"/>
  22. </div>
  23. <div class="form-group">
  24. <label>Lastname</label>
  25. <input type="text" name="lastname" class="form-control" required="required" />
  26. </div>
  27. <div class="form-group">
  28. <label>Address</label>
  29. <input type="text" name="address" class="form-control" required="required"/>
  30. </div>
  31. <center><button name="save" class="btn btn-primary">Save</button></center>
  32. </form>
  33. </div>
  34. <div class="col-md-8">
  35. <form method="POST" action="">
  36. <div class="form-inline">
  37. <input type="search" class="form-control" name="keyword" value="<?php echo isset($_POST['keyword']) ? $_POST['keyword'] : '' ?>" placeholder="Search here..." required=""/>
  38. <button class="btn btn-success" name="search">Search</button>
  39. <a href="./" class="btn btn-info">Reload</a>
  40. </div>
  41. </form>
  42. <br /><br />
  43. <?php include'search.php'?>
  44. </div>
  45. </div>
  46. </body>
  47. </html>

Creating the PDO Query for the Insertion of Data

This code contains the pdo query of the application. This code will store the form inputs to the MySQL database server. To make this just copy and paste the script below inside the text editor, then save it as "insert.php".

  1. <?php
  2. //require the database connection
  3. require_once 'conn.php';
  4.  
  5. if(ISSET($_POST['save'])){
  6. //setting up the variables
  7. $firstname = $_POST['firstname'];
  8. $lastname = $_POST['lastname'];
  9. $address = $_POST['address'];
  10.  
  11.  
  12. try{
  13. //setting attribute on the database handle
  14. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  15. //Inserstion Query
  16. $sql = "INSERT INTO `member`(firstname, lastname, address) VALUES ('$firstname', '$lastname', '$address')";
  17. //Execute Query
  18. $conn->exec($sql);
  19. }catch(PDOException $e){
  20. // Display error message
  21. echo $e->getMessage();
  22. }
  23. //Closing the connection
  24. $conn = null;
  25. //redirecting to the index page
  26. header("location: index.php");
  27.  
  28. }
  29. ?>

Creating the Main Function

This code contains the main function of the application which is the "Search Filter". This code will search data when the button is clicked or submitting the keyword. To do this just kindly write these block of codes inside the text editor, then save it as "search.php".

  1. <?php
  2. require 'conn.php';
  3. if(ISSET($_POST['search'])){
  4. ?>
  5. <table class="table table-bordered">
  6. <thead class="alert-info">
  7. <tr>
  8. <th>Firstname</th>
  9. <th>Lastname</th>
  10. <th>Address</th>
  11. </tr>
  12. </thead>
  13. <tbody>
  14. <?php
  15. $keyword = $_POST['keyword'];
  16. $query = $conn->prepare("SELECT * FROM `member` WHERE `firstname` LIKE '%$keyword%' or `lastname` LIKE '%$keyword%' or `address` LIKE '%$keyword%'");
  17. $query->execute();
  18. while($row = $query->fetch()){
  19. ?>
  20. <tr>
  21. <td><?php echo $row['firstname']?></td>
  22. <td><?php echo $row['lastname']?></td>
  23. <td><?php echo $row['address']?></td>
  24. </tr>
  25.  
  26.  
  27. <?php
  28. }
  29. ?>
  30. </tbody>
  31. </table>
  32. <?php
  33. }else{
  34. ?>
  35. <table class="table table-bordered">
  36. <thead class="alert-info">
  37. <tr>
  38. <th>Firstname</th>
  39. <th>Lastname</th>
  40. <th>Address</th>
  41. </tr>
  42. </thead>
  43. <tbody>
  44. <?php
  45. $query = $conn->prepare("SELECT * FROM `member`");
  46. $query->execute();
  47. while($row = $query->fetch()){
  48. ?>
  49. <tr>
  50. <td><?php echo $row['firstname']?></td>
  51. <td><?php echo $row['lastname']?></td>
  52. <td><?php echo $row['address']?></td>
  53. </tr>
  54.  
  55.  
  56. <?php
  57. }
  58. ?>
  59. </tbody>
  60. </table>
  61. <?php
  62. }
  63. ?>

There you have it, we successfully created a "Search Filter" using PDO. I hope that this simple tutorial helps you with what you are looking for. For more projects and tutorials just kindly visit and explore this site.

Enjoy Coding!

You can also download my working source code that I have created for this tutorial. Just click the download button below.

Comments

Submitted byzezzus (not verified)on Thu, 05/13/2021 - 20:59

Hi, I am a total newbie, and I am learning all this magic. When you write:
  1. $ keyword = $ _POST ['keyword'];
  2. $ query = $ conn-> prepare ("SELECT * FROM` x` WHERE `x` LIKE '% $ keyword%' or` x` LIKE '% $ keyword%' ");
  3. $ query-> execute ();
  4. while ($ row = $ query-> fetch ()) {
  5. ?>
is it a way to indicate the "syntax" of the search? That is to prevent SQL Injections? If yes or no, I have read that, the code to block is $ x = mysql_real_escape_string ($ x); it's correct? Maybe, between the lines of the code you put there is but I am not able to see it ?? Thank you

Add new comment