Vue.js Fetch Data from MySQL Database using PHP
Submitted by nurhodelta_17 on Friday, December 8, 2017 - 21:27.
Getting Started
In this tutorial, I've used Bootstrap CDN, so you need internet connection for it to work.Creating our Database
1. Open phpMyAdmin. 2. Click databases, create a database and name it as crud. 3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.- CREATE TABLE `members` (
- `memid` INT(11) NOT NULL AUTO_INCREMENT,
- `firstname` VARCHAR(30) NOT NULL,
- `lastname` VARCHAR(30) NOT NULL,
- PRIMARY KEY(`memid`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Inserting Data into our Database
Next. we're gonna insert sample data into our database. These are the data that we are going to fetch in this tutorial. 1. Click database crud that we have created earlier. 2. Click SQL and paste the ff codes:- INSERT INTO `members` (`memid`, `firstname`, `lastname`) VALUES
- (1, 'neovic', 'devierte'),
- (2, 'gemalyn', 'cepe');
index.php
This is we're we show the data that we are fetching in the form of table.- <!DOCTYPE html>
- <html>
- <head>
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
- </head>
- <body>
- <div class="container">
- <div id="members">
- <div class="col-md-8 col-md-offset-2">
- <div class="row">
- <div class="col-md-12">
- <h2>Member List
- </h2>
- </div>
- </div>
- <table class="table table-bordered table-striped">
- <thead>
- </thead>
- <tbody>
- <tr v-for="member in members">
- <td>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- </div>
- </body>
- </html>
api.php
This is our PHP API code that contains data from our database.- <?php
- $conn = new mysqli("localhost", "root", "", "crud");
- if ($conn->connect_error) {
- }
- $crud = 'read';
- $crud = $_GET['crud'];
- }
- if($crud = 'read'){
- $sql = "select * from members";
- $query = $conn->query($sql);
- while($row = $query->fetch_array()){
- }
- $out['members'] = $members;
- }
- $conn->close();
- ?>
app.js
Lastly, this is our Vue.js code that fetches data from our API.- var app = new Vue({
- el: '#members',
- data:{
- members: []
- },
- mounted: function(){
- this.getAllMembers();
- },
- methods:{
- getAllMembers: function(){
- axios.get("api.php")
- .then(function(response){
- //console.log(response);
- app.members = response.data.members;
- });
- }
- }
- });
Comments
Add new comment
- Add new comment
- 2028 views