Questions Hub

Fetch Data in PHP using Vue.js

Introduction:  In this article, I’ll walk you through the process of effortlessly fetching data from a MySQL database using PHP and Vue.js. By following these steps, you’ll seamlessly integrate Vue.js with PHP and efficiently manage data retrieval in your web applications.

 

Fetch Data in PHP using Vue.js

Folder Structure:


 

Follow these steps to set up your environment:

  1. Access http://localhost/phpmyadmin/ via your web browser.
  2. Create a new database named “vue_data“.
  3. Execute the provided SQL query within the “vue_data” database:
CREATE TABLE `student` (
`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` TEXT NOT NULL,
`email` TEXT NOT NULL,
`message` TEXT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

 

Add Data to Database:

Insert the following data into the “student” table:

INSERT INTO `student` (`id`, `name`, `email`, `message`) VALUES
(1, 'sachin', '[email protected]', 'hey i am sachin'),
(2, 'ankit', '[email protected]', 'hey ankit'),
(3, 'tina', '[email protected]', 'hey i am tina'),
(4, 'Rohit', '[email protected]', 'Hello i am rohit');

 

Creating Configuration File:

  1. Create a file named config.php.
  2. Paste the following code into config.php:
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'vue_data');
 
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>

 

Creating Fetch Script:

  1. Create a file named fetch.php.
  2. Paste the provided code into fetch.php:
<?php  
//Database 
require "config.php"; 

 $output = array();  
 $query = "SELECT * FROM student";  
 $result = mysqli_query($link, $query);  
   
      while($row = mysqli_fetch_array($result))  
      {  
           $output[] = $row;  
      }  
      echo json_encode($output);  
  
 ?>

 

Creating HTML & Vue.js Code:

  1. Create a file named index.html.
  2. Paste the provided code into index.html:
<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
  <title>Vue js CRUD</title>
</head>
<body>

<div class="container my-5" id="app" style="width:660px;">
  <h1 class="text-center">Vue js CRUD</h1>

<!-- DISPLAY DATA HERE -->
  <h1>Data Records</h1>
  <table class="table">
    <thead>
      <tr>
        <th scope="col">ID</th>
        <th scope="col">NAME</th>
        <th scope="col">EMAIL</th>
        <th scope="col">MESSAGE</th>
        <th scope="col">Update</th>
        <th scope="col">Delete</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="student in students" :key="student.id">
        <th>{{ student.id }}</th>
        <td>{{ student.name }}</td>
        <td>{{ student.email }}</td>
        <td>{{ student.message }}</td>
        <td><button type="button" class="btn btn-warning btn-sm" v-on:click="update(student.id)" data-bs-toggle="modal" data-bs-target="#exampleModal">Update</button></td>
        <td><button type="button" class="btn btn-danger btn-sm" v-on:click="deletee(student.id)">Delete</button></td>
      </tr>
    </tbody>
  </table>


</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <!-- Include Axios library -->
<script>
  const app = Vue.createApp({
    data() {
      return {
        students: [],
      }
    },
    
    mounted() {
      this.fetchData();
    },
    
    methods: {
      fetchData() {
        axios.get('fetch.php')
          .then(response => {
            this.students = response.data;
          })
          .catch(error => {
            console.error('Error fetching data:', error);
          });
      },
      
}

  });
  app.mount('#app');
</script>
</body>
</html>

 

Conclusion:

By following these steps, you’ve learned how to seamlessly fetch data from a MySQL database using Vue.js and PHP. Implementing this approach will enable you to efficiently manage data retrieval in your web applications.