Fetch Data in PHP using Vue.js
In this article, we’ll walk through the process of fetching data from a MySQL database using PHP and Vue.js. This tutorial is designed for developers looking to build dynamic web applications that require seamless data retrieval from a server-side database and display it on the front end using Vue.js. / Fetch Data in PHP using Vue.js
Setting Up Your Environment
Before we begin coding, it’s important to set up your development environment correctly. This ensures that all components work together smoothly.
1. Folder Structure
Start by organizing your project files in a clear and logical structure. Here’s an example:
/project-root /config.php /fetch.php /index.html
Note: This structure keeps your configuration, data-fetching logic, and front-end code neatly organized.
2. Create the Database
The first step in our setup is to create a MySQL database where the data will be stored.
- Open your web browser and navigate to http://localhost/phpmyadmin/. This is the interface for managing your MySQL databases.
- Click on “Databases” and create a new database named vue_data.
- After creating the database, select it and run the following SQL query to create a student table:
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;
Note: This table will store the students’ data, including their ID, name, email, and message.
3. Add Data to the Database
To work with data retrieval, we need some sample data in our student table. Insert the following data into the 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');
Note: This query adds four records to the student table, which we’ll later retrieve and display on the front end.
Creating the Configuration File
The config.php file will handle the database connection settings. Here’s how to set it up:
- Create config.php
- Copy this code and paste it into your file.
<?php // Database credentials define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'vue_data'); // Attempt to connect to the 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()); } ?>
Note: In your project root directory, create a file named config.php and add the following code, This script sets up a connection to your MySQL database using the MySQLi extension. It will terminate with an error message if the connection fails.
Creating the Fetch Script
The fetch.php script will handle the retrieval of data from the MySQL database and send it back as a JSON response.
- Create fetch.php
- Copy this code and paste it into your file.
<?php // Include database configuration 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); // Close the database connection mysqli_close($link); ?>
Note: Create a file named fetch.php in your project root and add the following code, This script queries the student table, fetches all rows, and encodes them into a JSON format, which will be returned to the front end. The mysqli_fetch_array function retrieves each row as an associative array, making it easy to work with in JavaScript.
Creating the HTML & Vue.js Code
The index.html file will serve as the front end of your application, displaying the data fetched from the database.
- Create index.html
- Copy this code and paste it into your file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/> <title>Vue.js Data Fetching</title> </head> <body> <div class="container my-5" id="app" style="width:660px;"> <h1 class="text-center">Vue.js Data Fetching</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> <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>
Note: Create a file named index.html and add the following content, This HTML file includes a Bootstrap-styled table that displays data fetched from the MySQL database. Vue.js is used to handle the data binding, and Axios is used to make the GET request to fetch.php to retrieve the data. When the page loads, the fetchData method is automatically called to populate the table with data from the database.
Conclusion
By following these steps, you’ve successfully learned how to fetch data from a MySQL database using PHP and Vue.js. This approach enables efficient data retrieval and display in your web applications, providing a smooth and responsive user experience. Whether you’re building a simple data listing page or a complex data-driven application, this technique lays a strong foundation for integrating front-end and back-end technologies.
Read Also: Insert Data in PHP using Vue.js
Feel free to expand on this example by adding features such as pagination, filtering, or search functionality. Happy coding!