Autocomplete with Suggestion Input using PHP, Vue.js, and MYSQL Database Tutorial

Introduction

In this tutorial, you will learn how to create an Autocomplete with suggestions input using PHP, Vue (Vue.js), and MySQL Database. The tutorial aims to provide IT/CS students or new programmers a reference for improving their web applications' client-side functionalities using Vue. Here, snippets are provided and a sample source code that demonstrates the main goal of this tutorial is also provided and is free to download.

What is Autocomplete with Suggestions Input?

In web applications, inputs with autocomplete with suggestions are commonly part of it to give the en-users a better experience while using the application and make it more efficient. This kind of input is mostly used for search boxes and input that queries options.

How to Autocomplete with Suggestions Input using Vue, PHP, and MySQL?

Autocomplete with Suggestions Input using Vue, PHP, and MySQL can be achieved in a few JavaScript and PHP lines of code. Like my past posted tutorial entitled (Live Search using PHP and Vue.JS Tutorial), suggestions data will be retrieved using the Fetch API and list it below the input.

Database

For this tutorial, let's assume that we have a database named dummy_db and have a MySQL Schema and table data using the snippet below.

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

Database Connection

Create a PHP file in your source code folder and save it as db-connect.php. This file contains the PHP Script for connecting the application to the database. See the following snippet.

  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. }<?php
  12. $host = "localhost";
  13. $username = "root";
  14. $pw = "";
  15. $db_name = "dummy_db";
  16.  
  17. $conn = new mysqli($host, $username, $pw, $db_name);
  18.  
  19. if(!$conn){
  20.     die("Database Connection Failed");
  21. }

Suggestions Query Script

Next, create another PHP File and save it as getLanguages.php. This file contains the PHP code that queries the suggested languages/data from the database table. This is a simple PHP API where the Fetch API will request the suggested data.

  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();

Interface

Next, create the page interface where you will display your autocomplete with suggestions input. The snippet I provided below uses CDNs for loading some external libraries for the design and Vue. Make sure to be connected to the internet when using the snippet to run it properly.

index.php

  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>Auto Complete | 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.         #suggestion-field>.position-absolute {
  21.             height: 30vh;
  22.             overflow: auto;
  23.         }
  24.     </style>
  25. </head>
  26.     <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  27.         <div class="container">
  28.             <a class="navbar-brand" href="./">Auto Complete</a>
  29.             <div>
  30.                 <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  31.             </div>
  32.         </div>
  33.     </nav>
  34.     <div class="container-fluid px-5 my-3" id="SampleApp">
  35.         <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  36.             <h3 class="text-center"><b>Auto Complete using PHP and Vue.js</b></h3>
  37.             <div class="d-flex w-100 justify-content-center">
  38.                 <hr class="w-50">
  39.             </div>
  40.             <div class="card rounded-0 shadow mb-3">
  41.                 <div class="card-body">
  42.                     <div class="container-fluid">
  43.                         <div class="mb-3">
  44.                             <div class="input-group flex-nowrap">
  45.                                 <input type="search" class="form-control rounded-0" placeholder="Search Prgramming Laguage" aria-label="Search" aria-describedby="addon-wrapping" v-model="search" @input="searchLanguages()">
  46.                                 <span class="input-group-text rounded-0" id="addon-wrapping"><i class="fa-solid fa-search"></i></span>
  47.                             </div>
  48.                             <div id="suggestion-field" class="position-relative w-100" v-show="suggestions">
  49.                                 <div class="position-absolute w-100 border">
  50.                                     <div id="suggestion-lis" class="list-group">
  51.                                         <a class="list-group-item list-group-item-action" href="#" v-for="language in languages" @click="getLanguage(language)">
  52.                                             {{language}}
  53.                                         </a>
  54.                                         <div class="list-group-item text-center text-muted" v-if="languages.length <= 0"><i>No suggestion found</i></div>
  55.                                     </div>
  56.                                 </div>
  57.                             </div>
  58.                         </div>
  59.                     </div>
  60.                 </div>
  61.             </div>
  62.         </div>
  63.     </div>
  64.     <script src="app.js"></script>
  65. </body>
  66. </html>

JavaScript

Lastly, create a new file and save it as app.js. The file contains the JavaScript codes that initiate the autocomplete with suggestions input using VueJS. It contains the method of retrieving the suggestions and selecting the input data.

  1. const { createApp } = Vue
  2.  
  3. /**
  4.     * Create Vue App to the selected Element
  5.     */
  6. var app = createApp({
  7.     /**
  8.         * App Data
  9.         */
  10.     data() {
  11.         return {
  12.             languages: [],
  13.             search:'',
  14.             suggestions:false
  15.         }
  16.  
  17.     },
  18.     /**
  19.         * App Methods
  20.         */
  21.     methods:{
  22.         searchLanguages(){
  23.             /**
  24.                 * Query Suggestions
  25.                 */
  26.             if(this.search == ""){
  27.                 this.languages = []
  28.                 this.suggestions = false
  29.             }else{
  30.                 var formData = new FormData();
  31.                 formData.append('search', this.search)
  32.                 fetch('getLanguages.php',{
  33.                     method:'POST',
  34.                     body: formData
  35.                 })
  36.                 .then(response => {
  37.                     return response.json()
  38.                 })
  39.                 .then(data => {
  40.                     this.languages = Object.values(data)
  41.                     this.suggestions = true
  42.                 } )
  43.             }
  44.  
  45.         },
  46.         getLanguage(language){
  47.             /**
  48.                 * Write selected suggestion to the search input
  49.                 */
  50.             this.search = language
  51.             this.languages = []
  52.             this.suggestions = false
  53.         }
  54.     }
  55. }).mount('#SampleApp')

That's it! the suggestion list will be triggered upon inputting in the provided text field. The selected suggestion will be automatically written on the input when clicking the item.

Snapshots

The snippets that I have provided above will result in the following snapshots.

Main Page Interface

Autocomplete with Suggestions Input using PHP and VueJS

Autocomplete with Suggestions Input

Autocomplete with Suggestions Input using PHP and VueJS

I have provided also the source code zip file that I created for this tutorial. You can download it by clicking the Download Button below this article. Feel free to download and modify it the way you wanted.

That's the end of this tutorial. I hope this Autocomplete with Suggestions Input Tutorial using PHP, VueJS, and MySQL will help you with what you are looking for and that you'll find this useful for your current and future projects.

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

Happy Coding:)

Add new comment