Fetch records from MySQL Database with Vue.js and PHP

Data selection is one of the basic requirements when creating a dynamic website.

Mainly data is fetched from the database on page refresh but without page refresh require to send AJAX request.

I am using the Axios package to send the AJAX request.

In this tutorial, I show how you can fetch records from MySQL database using Vue.js and PHP with the Axios package.

Fetch records from MySQL Database with Vue.js and PHP


Contents

  1. Table structure
  2. Configuration
  3. Download & Include
  4. HTML
  5. PHP
  6. Script
  7. Demo
  8. Conclusion

1. Table structure

I am using users table in the example.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a new config.php file for the database configuration.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

3. Download & Include

  • Download Axios package from GitHub. or you can also use CDN (https://unpkg.com/axios/dist/axios.min.js).
  • Now, include axios.min.js with vue.js in the <head> section.
<script src="vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

4. HTML

Create two buttons and a textbox.

On the first button define @click='allRecords()' and on the second define @click='recordByID()' events.

Add v-model='userid' in the textbox.

Use v-for='user in users' on <tr> to list records.

  • The first button is used to send a GET request without a parameter.
  • The second button is used to send a GET request with parameters.

Completed Code

<div id='myapp'>
 
  <!-- Select All records -->
  <input type='button' @click='allRecords()' value='Select All users'>
  <br><br>

  <!-- Select record by ID -->
  <input type='text' v-model='userid' placeholder="Enter Userid between 1 - 24">
  <input type='button' @click='recordByID()' value='Select user by ID'>
  <br><br>

  <!-- List records -->
  <table border='1' width='80%' style='border-collapse: collapse;'>
    <tr>
      <th>Username</th>
      <th>Name</th>
      <th>Email</th>
    </tr>

    <tr v-for='user in users'>
      <td>{{ user.username }}</td>
      <td>{{ user.name }}</td>
      <td>{{ user.email }}</td>
    </tr>
  </table>
 
</div>

5. PHP

Create a new ajaxfile.php.

Fetch records from the users table and initialize $response Array.

Assign " id =".$_GET['userid'] to $where if $_GET['userid'] is passed.

Return $response in JSON response.

Completed Code

<?php
include "config.php";

$condition = "1";
if(isset($_GET['userid'])){
   $condition = " id=".$_GET['userid'];
}
$userData = mysqli_query($con,"select * from users WHERE ".$condition);

$response = array();

while($row = mysqli_fetch_assoc($userData)){

   $response[] = $row;
}

echo json_encode($response);
exit;

6. Script

Syntax – Axios GET request without parameter  –

axios.get('path')
.then(function(response){
   // Handle response
}).catch(function(error){
   // Error handling
});

Syntax – Axios GET request with parameter  –

axios.get('path',{
  params:{
     parameter1: value,
     parameter2: value,
     .... 
  }
})
.then(function(response){
   // Handle response
}).catch(function(error){
   // Error handling
});

OR

axios.get('path?variable1=value1&variable2=value2&...')
.then(function(response){
   // Handle response
}).catch(function(error){
   // Error handling
});

Define two variable users and userid.

Define two methods –

  • allRecords – Send AJAX request to fetch all records and assign response.data to app.users. Here, app.users pointing to defined data variable.
  • recordByID – Pass the textbox value this.userid in params: {
    userid: this.userid }
    . Assign response.data in app.users on successful callback.

Completed Code

var app = new Vue({
  el: '#myapp',
  data: {
    users: "",
    userid: 0
  },
  methods: {
    allRecords: function(){

      axios.get('ajaxfile.php')
      .then(function (response) {
         app.users = response.data;
      })
      .catch(function (error) {
         console.log(error);
      });
    },
    recordByID: function(){
      if(this.userid > 0){
 
        axios.get('ajaxfile.php', {
           params: {
             userid: this.userid
           }
        })
        .then(function (response) {
           app.users = response.data;
        })
        .catch(function (error) {
           console.log(error);
        });
      }
    }
  }
})

7. Demo

View Demo


8. Conclusion

Use params option to pass data to AJAX request or you can directly pass it with the path.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

28 thoughts on “Fetch records from MySQL Database with Vue.js and PHP”

  1. Hello Yogesh
    thank for this wonderful tutorial.
    I have a probleme , i copied this source but when i try the form i have not the username, name,email, are not displayed, only the rows of the table diplayed but see empty.

    Thank for your help

    Reply
    • Hi Serna,
      Add console.log(‘success : ‘ + JSON.stringify(response.data) ); in axios then function to check any data returning from PHP file.

      Are you viewing any error in the browser console?

      Reply
  2. Hi Yogesh , thank for reply

    i add this in bottom of axios.min.js
    console.log(‘success : ‘ + JSON.stringify(response.data) );
    and in console i have this message :
    “ReferenceError: response is not defined”

    however I copy the files from your sources and copied the index.html here
    https://makitweb.com/demo/vuejs_fetch_data/
    your page works but me in localhost i have just the line of the tab but empty

    for infos i have wampserver 3.1.0 , php 7.1.9 mysql 5.7.19

    thank Yogesh for help

    Serna

    Reply
  3. Hi Yogesh ,
    I put an echo on the json encode and it seems to work
    i have this output from ajaxfile.php
    {“id”:”1″,”username”:”yssyogesh”,”name”:”Yogesh singh”,”email”:”yssyogesh_gmail.com”}{“id”:”2″,”username”:”sonarika”,”name”:”Sonarika”,”email”:”sonarika_gmail.com”}{“id”:”3″,”username”:”vishal”,”name”:”Vishal Sahu”,”email”:”vishal_gmail.com”} etc..

    but this data do not show in the div

    thank Yogesh to take time to explain why your code does not work in my localhost

    Reply
    • Hi Yogesh,
      I modified the ajaxfile.php file a bit and it works now. ( i use PDO)
      at the end of the script before the loop :
      $result = [];
      and

      congratulations for your excellent tutorial !

      Reply
      • Hi Serna,
        I have the same problem with ajaxfile.php, I would try your solution, but I haven’t understud you modification in ajaxfile.php
        Could you explain what you made?
        Many thanks
        Aldo

  4. Hi! I’m having trouble getting this to run. I keep getting a 404 error:

    spread.js:25 GET http://localhost:8080/ajaxfile.php?username=janeDoe&password=1234 404 (Not Found)

    It seems there is something wrong with the line of code where it says axios.get(….).
    Here’s my code:
    login: function(){

    axios.get(‘ajaxfile.php’ , {
    params: {
    username: this.username,
    password: this.password
    }
    })
    .then(function (response) {
    //app.users = response.data;
    // console.log(response);
    console.log(‘success : ‘ + JSON.stringify(response.data) );
    })
    .catch(function (error) {
    console.log(error);
    });

    },

    someone please help! I’ve been working on this for hours…..Thank you

    Reply
  5. Thank you for this tutorial i find it very useful for me because i try to learn some code.

    1)Can please anyone tell me how to make the text at the form as a dropmenu? I dont want to write 1,2,3….. but to have a dropmenu?

    2)Also is it possible to remove button and show the results instantly without press the button when select a user id at dropmenu?
    Thank you!

    Reply
  6. Thanks, great start for me moving from jQuery ajax to Vue/axios 🙂
    Is there a Create and Update tutorials as well?
    Or is it just to use POST?
    Greetings
    Henning

    Reply
  7. Thank you for this. I’m transition from a “functions” (I think it’s called) PHP mindset of PHP 4,5,7 and been eager to learn a JS Framework. This article has really helped me get a better handle on Vuejs/ JS Frameworks.

    Thanks very much. 🙂

    Reply
  8. Hi Yogesh,
    I’m having some difficulties, I never worked with PHP before.
    I have done exactly as you did, but for some reason instead of returning values from a database it returns the content of the ajaxfile.php itself inside response.data . Do you have any idea why it is doing this?
    Thanks for your videos, they were really helpful to learn PHP with Vue.

    Reply
  9. Grettings Yogesh!

    I’m having a problem echoing the json_encode result into my VueJS app.
    It’s printing the file rather than the json_encode result.
    What am I doing wrong?

    This is the console log result:
    success : ” false);\r\n\r\n$result = $conn->query(\”SELECT * FROM `menu_temas`\”);\r\n$menu_temas = array();\r\n\r\nwhile ($row = $result->fetch_assoc()) {\r\n $menu_temas[] = $row;\r\n}\r\n\r\necho json_encode($menu_temas);\r\nexit;”

    Thank you for the tutorial, it was very clear 🙂

    Reply
  10. Thanks for this tutorial, but finally i only get “network error” from axios.. running the php scripts manually works fine. Maybe i’ll find a solution sometimes

    Reply

Leave a Comment