Live Search using PHP and Vue.JS Tutorial

Introduction

In this tutorial, you will learn how to create a Live Search using PHP Language, Vue.js, and Fetch API. The tutorial aims to provide a reference to the IT/CS Students and new programmers on how they can implement a live searching feature on their PHP Projects. The Live Search allows the end-users to search the data that matches or column data containing the searched term and update the data on the client side without leaving or reloading the page. Here, snippets are provided and a sample web application program source code is free to download.

What is Vue.js

Vue.js is commonly called Vue. It is a free and open-source front-end model-view-viewmodel JavaScript framework for creating user interfaces and single-page programs. Visit https://vuejs.org/ to know more and read the documentation on how to use it.

How to Create A Live Search using PHP, Vue.js, and Fetch API?

The Live Searching feature is one of the common features that can be found in web applications. It is always used to filter out or locate data from a list or bulk of data that fits the searched term or word(s). On a web application that loads and retrieves dynamic data using PHP, a live search can be achieved using Vue.js and Fetch API. Fetch API helps to retrieve the search data on the client's page background without leaving the page, and Vue updates the data displayed on the current page.

Example

MySQL Schema

Assuming that we have the following MySQL Schema and Data and the database name is dummy_db.

  1. CREATE TABLE `languages` (
  2. `id` int(30) NOT NULL,
  3. `name` varchar(250) NOT NULL
  4.  
  5. INSERT INTO `languages` (`id`, `name`) VALUES
  6. (1, 'PHP'),
  7. (2, 'HTML'),
  8. (3, 'CSS'),
  9. (4, 'JavaScript'),
  10. (5, 'Python'),
  11. (6, 'C++'),
  12. (7, 'C#'),
  13. (8, '.NET'),
  14. (9, 'VB'),
  15. (10, 'ASP.NET'),
  16. (11, 'Java');
  17.  
  18. ALTER TABLE `languages`
  19. ADD PRIMARY KEY (`id`);
  20.  
  21. ALTER TABLE `languages`

Database Connection

Next, we need to create a PHP File that connects our application to the database we created.

db-connect.php

  1. <?php
  2. $host = "localhost";
  3. $username = "root";
  4. $pw = "";
  5. $db_name = "dummy_db";
  6.  
  7. $conn = new mysqli($host, $username, $pw, $db_name);
  8.  
  9. if(!$conn){
  10. die("Database Connection Failed");
  11. }

Interface

Here is the example snippet for the interface of the application that we will make to demonstrate the Live Search using PHP, Vue.js, and Fetch API. Take note that scripts/code on the snippet that I created, I used CDNs for loading the Bootstrap Framework and Vue.js. An Internet connection is a must in order for the snippet will work properly.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Live Search | PHP & Vue.JS</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  10. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  11. <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  12. <style>
  13. html, body{
  14. min-height:100%;
  15. width:100%;
  16. }
  17. tbody:empty:after{
  18. content:'No records found'
  19. }
  20. </style>
  21. </head>
  22. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  23. <div class="container">
  24. <a class="navbar-brand" href="./">Live Search</a>
  25. <div>
  26. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  27. </div>
  28. </div>
  29. </nav>
  30. <div class="container-fluid px-5 my-3" id="SampleApp">
  31. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  32. <h3 class="text-center"><b>Live Search using PHP and Vue.js</b></h3>
  33. <div class="d-flex w-100 justify-content-center">
  34. <hr class="w-50">
  35. </div>
  36. <div class="card rounded-0 shadow mb-3">
  37. <div class="card-body">
  38. <div class="container-fluid">
  39. <div class="mb-3">
  40. <div class="input-group flex-nowrap">
  41. <input type="search" class="form-control rounded-0" placeholder="Search" aria-label="Search" aria-describedby="addon-wrapping" v-model="search" @keyup="searchLanguages()">
  42. <span class="input-group-text rounded-0" id="addon-wrapping"><i class="fa-solid fa-search"></i></span>
  43. </div>
  44. </div>
  45. <div class="list-group rounded-0">
  46. <!-- Loop All Programming Languages using VueJS -->
  47. <div class="list-group-item rounded-0" v-for="language in languages">
  48. {{language}}
  49. </div>
  50. <!-- End of Loop -->
  51.  
  52. <!-- Display Message if There no data has been retrieved -->
  53. <div class="list-group-item text-muted text-center" v-if="languages.length <= 0">
  54. No data found
  55. </div>
  56. <!-- end -->
  57. </div>
  58. </div>
  59. </div>
  60. </div>
  61. </div>
  62. </div>
  63. <script src="app.js"></script>
  64. </body>
  65. </html>

PHP API

Next, we will create the PHP File that contains the script of retrieving the data from the database. The snippet below demonstrates a SQL Query that automatically detects if there's a search term/word has sent. If the search term/word exists on the request, the query will use Where Clause and Like Operator to retrieve only the data row that fits to the given search word/term.

getLanguages.php

  1. <?php
  2. require_once('db-connect.php');
  3. /**
  4.   * Search Language where name is like the search term
  5.   */
  6. $swhere = "";
  7.  
  8. if(isset($_POST['search']) && !empty($_POST['search'])){
  9. $swhere = " WHERE `name` LIKE '%{$_POST['search']}%' ";
  10. }
  11. $sql = "SELECT * FROM `languages` {$swhere} order by `name` asc";
  12. $query = $conn->query($sql);
  13. $languages = [] ;
  14. if($query->num_rows > 0){
  15. $languages = array_column($query->fetch_all(MYSQLI_ASSOC), 'name');
  16. }
  17.  
  18. echo json_encode($languages);
  19. $conn->close();

JavaScript

Next is to create the Vue Application Script using JavaScript. The snippet below initiates the Vue Application using the #SampleApp element on the user interface. It also contains the methods and data for loading the sample data on the interface.

app.js

  1. const { createApp } = Vue
  2.  
  3. /**
  4.   * Create Vue App to the selected Element
  5.   */
  6. createApp({
  7. /**
  8.   * App Data
  9.   */
  10. data() {
  11. return {
  12. languages: [],
  13. search:''
  14. }
  15.  
  16. },
  17. /**
  18.   * App Methods
  19.   */
  20. methods:{
  21.  
  22. /**
  23.   * Retrieve All Data From Database using Fetch API
  24.   */
  25. getLanguages(){
  26. fetch('getLanguages.php')
  27. .then(response => {
  28. return response.json()
  29. })
  30. .then(data => {
  31. this.languages = Object.values(data)
  32. } )
  33. },
  34. /**
  35.   * Retrieve All Data that Name is like the Search Term From Database using Fetch API
  36.   */
  37. searchLanguages(){
  38. var formData = new FormData();
  39. formData.append('search', this.search)
  40. fetch('getLanguages.php',{
  41. method:'POST',
  42. body: formData
  43. })
  44. .then(response => {
  45. return response.json()
  46. })
  47. .then(data => {
  48. this.languages = Object.values(data)
  49. } )
  50. }
  51. },
  52. created: function() {
  53. /**
  54.   * Load All Data when app is created
  55.   */
  56. this.getLanguages()
  57. }
  58. }).mount('#SampleApp')

The Live Search functionality will be automatically triggered when the user inputs a character/term/word on the search box. Then, the application will request new data in the background and update the list of data after receiving the new data.

Sample Snapshots

Here are some of the page snapshots using the snippets above.

Complete Data

Live Search using PHP, Vue.js, and Fetch API

Filtered Data

Live Search using PHP, Vue.js, and Fetch API

No Search Result

Live Search using PHP, Vue.js, and Fetch API

DEMO VIDEO

I have provided the source code zip file that I created for this tutorial. You can download it by clicking the Download Button below this article.

That's the end of this tutorial! I hope this Live Search using PHP, Vue.js, and Fetch API Tutorial helps you with what you are looking for and that you'll find it useful for your current and future Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment