Welcome folks today in this blog post we will be building a user crud in bootstrap 4 modal window using vue.js and php. For this we will be using php PDO & Mysql Database. All the full source code of the application is shown below.
Get Started
In order to get started you need to download xammp control panel for apache php server and also the mysql database as well. And after downloading it you need to start the apache php server and mysql as well as shown below
And after that we will be creating the database and the tables required for this crud web application in vue.js.
Creating Database and Tables in PHPMyAdmin
Now guys you need to copy paste the below sql code inside the phpmyadmin section as shown below
In this section you need to copy paste the below code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
CREATE DATABASE testing; use testing; CREATE TABLE `tbl_sample` ( `id` int(11) NOT NULL, `first_name` varchar(250) NOT NULL, `last_name` varchar(250) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_sample` -- INSERT INTO `tbl_sample` (`id`, `first_name`, `last_name`) VALUES (1, 'John', 'Smith'), (2, 'Peter', 'Parker'), (4, 'Donna', 'Huber'); -- -- Indexes for dumped tables -- -- -- Indexes for table `tbl_sample` -- ALTER TABLE `tbl_sample` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tbl_sample` -- ALTER TABLE `tbl_sample` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; |
As you can see we are first of all creating the database testing and then we are creating the table tbl_sample and inside that we have three columns id, first_name and last_name fields. And ID is the primary key which will be auto incremented every time a new record is inserted into the table. And also with the help of Insert statement we are also adding three records already in the table.
Directory Structure of App
Now I will be showing you the files and folders of this crud web app. The screenshot is shown below
Now we will be building the index.html
file for this app and copy paste the below code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>PHP Insert Update Delete with Vue.js</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> </body> </html> |
First of all inside this index.html
you can see we are including all the libraries cdn such as bootstrap 4, axios library which is http client library to make http requests and also we are including the vue.js cdn library.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<div class="container" id="crudApp"> <br /> <h3 align="center">Delete or Remove Data From Mysql using Vue.js with PHP</h3> <br /> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-md-6"> <h3 class="panel-title">Sample Data</h3> </div> <div class="col-md-6" align="right"> <input type="button" class="btn btn-success btn-xs" @click="openModel" value="Add" /> </div> </div> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table table-bordered table-striped"> <tr> <th>First Name</th> <th>Last Name</th> <th>Edit</th> <th>Delete</th> </tr> <tr v-for="row in allData"> <td>{{ row.first_name }}</td> <td>{{ row.last_name }}</td> <td><button type="button" name="edit" class="btn btn-primary btn-xs edit" @click="fetchData(row.id)">Edit</button></td> <td><button type="button" name="delete" class="btn btn-danger btn-xs delete" @click="deleteData(row.id)">Delete</button></td> </tr> </table> </div> </div> </div> </div> |
Designing the UI of App Using Bootstrap 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<div class="container" id="crudApp"> <br /> <h3 align="center">Delete or Remove Data From Mysql using Vue.js with PHP</h3> <br /> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-md-6"> <h3 class="panel-title">Sample Data</h3> </div> <div class="col-md-6" align="right"> <input type="button" class="btn btn-success btn-xs" @click="openModel" value="Add" /> </div> </div> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table table-bordered table-striped"> <tr> <th>First Name</th> <th>Last Name</th> <th>Edit</th> <th>Delete</th> </tr> <tr v-for="row in allData"> <td>{{ row.first_name }}</td> <td>{{ row.last_name }}</td> <td><button type="button" name="edit" class="btn btn-primary btn-xs edit" @click="fetchData(row.id)">Edit</button></td> <td><button type="button" name="delete" class="btn btn-danger btn-xs delete" @click="deleteData(row.id)">Delete</button></td> </tr> </table> </div> </div> </div> <div v-if="myModel"> <transition name="model"> <div class="modal-mask"> <div class="modal-wrapper"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" @click="myModel=false"><span aria-hidden="true">×</span></button> <h4 class="modal-title">{{ dynamicTitle }}</h4> </div> <div class="modal-body"> <div class="form-group"> <label>Enter First Name</label> <input type="text" class="form-control" v-model="first_name" /> </div> <div class="form-group"> <label>Enter Last Name</label> <input type="text" class="form-control" v-model="last_name" /> </div> <br /> <div align="center"> <input type="hidden" v-model="hiddenId" /> <input type="button" class="btn btn-success btn-xs" v-model="actionButton" @click="submitData" /> </div> </div> </div> </div> </div> </div> </transition> </div> </div> |
And inside this html we are displaying all the records coming from the mysql database and tables inside the browser. And also we have the update and delete buttons also to perform the CRUD operations. And also we have the popup window to edit the records. Here we are using all the bootstrap 4 classes. And now we need to define all these methods inside the javascript.
So here we are looping all the records inside the bootstrap 4 table using the v-for directive. And also we are rendering different blocks of code using the v-if directive. And then we are rendering different dynamic variables using the {{ }} syntax.
As you can see we are rendering the records in the bootstrap 4 table and also we are editing and creating the records in the popup window.
Writing the Vue.js Code
Now we will be writing the vue.js code for this app as shown below
app.js
Fetching all Data From Table
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var application = new Vue({ el: '#crudApp', data: { allData: '', myModel: false, actionButton: 'Insert', dynamicTitle: 'Add Data', }, methods: { fetchAllData: function () { axios.post('action.php', { action: 'fetchall' }).then(function (response) { application.allData = response.data; }); }, }, created: function () { this.fetchAllData(); } }); |
As you can see we are targeting the html
element in the dom where we are making the vue.js app. And then we are declaring the state variables inside the data block and then we have defined the methods section where we have defined the method which is called fetchAllData() which is calling the php
script called action.php in which we are making the post request in which we are passing the attribute called fetchAll and then we are getting the response from the php server. And we are calling the fetchAllData()
method inside the created section of the vue.js App.
PHP Code to Retrieve All Records From Table
Now guys we will be retrieving all the user records from the table. I will be showing you the php code which is shown below. Create a file called action.php
file and copy paste the below code
action.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php //action.php $connect = new PDO("mysql:host=localhost;dbname=testing", "root", ""); $received_data = json_decode(file_get_contents("php://input")); $data = array(); if($received_data->action == 'fetchall') { $query = " SELECT * FROM tbl_sample ORDER BY id DESC "; $statement = $connect->prepare($query); $statement->execute(); while($row = $statement->fetch(PDO::FETCH_ASSOC)) { $data[] = $row; } echo json_encode($data); } |
Firstly we are making the connection to the database using the PDO method and objects. Here inside the constructor we are passing the hostname,username,password and databasename.
Then as you can see we are checking the action
attribute value. If this equal to fetchall then we are making the sql query to select all the records from the table and then we are using the PDO prepared statements to insert the records into the table columns. And then we are executing the sql query. And after that we are converting the data coming from the table to an associative array. For looping this data we are using the while loop and then we are storing these results inside the $data[] variable. And then we are encoding this array to json() method back to the client.
Deleting the Records From the Table
Now we will be deleting a specific user record using it’s id. Now just add this below code inside app.js
file as shown below
1 2 3 4 5 6 7 8 9 10 11 |
deleteData:function(id){ if(confirm("Are you sure you want to remove this data?")) { axios.post('action.php', { action:'delete', id:id }).then(function(response){ application.fetchAllData(); }); } } |
As you can see inside this function we are showing the confirm modal window to ask the user to delete the user record or not. And then if user selects yes then we are making the post request using the axios http client library and we are again calling the same action.php
file and then we are sending the action attribute equal to delete and also we are providing a second parameter to id.
PHP Code to Delete Specific User Record Using it’s ID
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
if($received_data->action == 'delete') { $query = " DELETE FROM tbl_sample WHERE id = '".$received_data->id."' "; $statement = $connect->prepare($query); $statement->execute(); $output = array( 'message' => 'Data Deleted' ); echo json_encode($output); } |
As you can see we are writing the sql query to delete the record from the table where we are providing the id parameter and then we are executing the query. And then we are sending the json data to the client just informing that the user record has been deleted.
Inserting & Updating the User Records in the Table
Now guys we will be writing the method inside the vue.js to insert & update the user records in the table by calling the php script as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
openModel:function(){ application.first_name = ''; application.last_name = ''; application.actionButton = "Insert"; application.dynamicTitle = "Add Data"; application.myModel = true; }, submitData:function(){ if(application.first_name != '' && application.last_name != '') { if(application.actionButton == 'Insert') { axios.post('action.php', { action:'insert', firstName:application.first_name, lastName:application.last_name }).then(function(response){ application.myModel = false; application.fetchAllData(); application.first_name = ''; application.last_name = ''; }); } if(application.actionButton == 'Update') { axios.post('action.php', { action:'update', firstName : application.first_name, lastName : application.last_name, hiddenId : application.hiddenId }).then(function(response){ application.myModel = false; application.fetchAllData(); application.first_name = ''; application.last_name = ''; application.hiddenId = ''; }); } } else { alert("Fill All Field"); } } |
As you can see we are showing the modal popup window where we allow the user to enter the details of the user and then insert the details into the table. For this we are making the axios post request to the php action.php file and also passing the action attribute to insert. And also we are passing the whole object which contains the firstname and lastname. And also in the update operation we are passing the id of the user and also passing the firstname,lastname of the user.
PHP Code to Insert User Record in Table
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
if($received_data->action == 'insert') { $data = array( ':first_name' => $received_data->firstName, ':last_name' => $received_data->lastName ); $query = " INSERT INTO tbl_sample (first_name, last_name) VALUES (:first_name, :last_name) "; $statement = $connect->prepare($query); $statement->execute($data); $output = array( 'message' => 'Data Inserted' ); echo json_encode($output); } |
As you can see that we are first of all checking the action attribute value. If it’s equal to insert then we are simply writing the sql query to insert the user records passing the whole object of the user containing the firstname and lastname. And then we are executing the sql query using prepared statements. And after successful operation we are sending a json message to the client. And then encoding that message using json_encode() method.
PHP Code to Update Specific Record Using it’s ID
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
if($received_data->action == 'fetchSingle') { $query = " SELECT * FROM tbl_sample WHERE id = '".$received_data->id."' "; $statement = $connect->prepare($query); $statement->execute(); $result = $statement->fetchAll(); foreach($result as $row) { $data['id'] = $row['id']; $data['first_name'] = $row['first_name']; $data['last_name'] = $row['last_name']; } echo json_encode($data); } if($received_data->action == 'update') { $data = array( ':first_name' => $received_data->firstName, ':last_name' => $received_data->lastName, ':id' => $received_data->hiddenId ); $query = " UPDATE tbl_sample SET first_name = :first_name, last_name = :last_name WHERE id = :id "; $statement = $connect->prepare($query); $statement->execute($data); $output = array( 'message' => 'Data Updated' ); echo json_encode($output); } |
As you can see we are fetching the single user record value by passing the id to prefetch the details of the user inside the input fields for which we need to perform the update operation.
And then lastly if user presses the update operation we are executing the update sql query and passing the whole user object which is sent from the client to the php script. And here we execute the update sql query to update the user record.
Full Source Code
Wrapping it up I will be providing you the full source code of both the files index.html
and action.php
files
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>PHP Insert Update Delete with Vue.js</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <style> .modal-mask { position: fixed; z-index: 9998; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, .5); display: table; transition: opacity .3s ease; } .modal-wrapper { display: table-cell; vertical-align: middle; } </style> </head> <body> <div class="container" id="crudApp"> <br /> <h3 align="center">Delete or Remove Data From Mysql using Vue.js with PHP</h3> <br /> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-md-6"> <h3 class="panel-title">Sample Data</h3> </div> <div class="col-md-6" align="right"> <input type="button" class="btn btn-success btn-xs" @click="openModel" value="Add" /> </div> </div> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table table-bordered table-striped"> <tr> <th>First Name</th> <th>Last Name</th> <th>Edit</th> <th>Delete</th> </tr> <tr v-for="row in allData"> <td>{{ row.first_name }}</td> <td>{{ row.last_name }}</td> <td><button type="button" name="edit" class="btn btn-primary btn-xs edit" @click="fetchData(row.id)">Edit</button></td> <td><button type="button" name="delete" class="btn btn-danger btn-xs delete" @click="deleteData(row.id)">Delete</button></td> </tr> </table> </div> </div> </div> <div v-if="myModel"> <transition name="model"> <div class="modal-mask"> <div class="modal-wrapper"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" @click="myModel=false"><span aria-hidden="true">×</span></button> <h4 class="modal-title">{{ dynamicTitle }}</h4> </div> <div class="modal-body"> <div class="form-group"> <label>Enter First Name</label> <input type="text" class="form-control" v-model="first_name" /> </div> <div class="form-group"> <label>Enter Last Name</label> <input type="text" class="form-control" v-model="last_name" /> </div> <br /> <div align="center"> <input type="hidden" v-model="hiddenId" /> <input type="button" class="btn btn-success btn-xs" v-model="actionButton" @click="submitData" /> </div> </div> </div> </div> </div> </div> </transition> </div> </div> </body> </html> <script> var application = new Vue({ el:'#crudApp', data:{ allData:'', myModel:false, actionButton:'Insert', dynamicTitle:'Add Data', }, methods:{ fetchAllData:function(){ axios.post('action.php', { action:'fetchall' }).then(function(response){ application.allData = response.data; }); }, openModel:function(){ application.first_name = ''; application.last_name = ''; application.actionButton = "Insert"; application.dynamicTitle = "Add Data"; application.myModel = true; }, submitData:function(){ if(application.first_name != '' && application.last_name != '') { if(application.actionButton == 'Insert') { axios.post('action.php', { action:'insert', firstName:application.first_name, lastName:application.last_name }).then(function(response){ application.myModel = false; application.fetchAllData(); application.first_name = ''; application.last_name = ''; }); } if(application.actionButton == 'Update') { axios.post('action.php', { action:'update', firstName : application.first_name, lastName : application.last_name, hiddenId : application.hiddenId }).then(function(response){ application.myModel = false; application.fetchAllData(); application.first_name = ''; application.last_name = ''; application.hiddenId = ''; }); } } else { alert("Fill All Field"); } }, fetchData:function(id){ axios.post('action.php', { action:'fetchSingle', id:id }).then(function(response){ application.first_name = response.data.first_name; application.last_name = response.data.last_name; application.hiddenId = response.data.id; application.myModel = true; application.actionButton = 'Update'; application.dynamicTitle = 'Edit Data'; }); }, deleteData:function(id){ if(confirm("Are you sure you want to remove this data?")) { axios.post('action.php', { action:'delete', id:id }).then(function(response){ application.fetchAllData(); }); } } }, created:function(){ this.fetchAllData(); } }); </script> |
action.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
<?php //action.php $connect = new PDO("mysql:host=localhost;dbname=testing", "root", ""); $received_data = json_decode(file_get_contents("php://input")); $data = array(); if($received_data->action == 'fetchall') { $query = " SELECT * FROM tbl_sample ORDER BY id DESC "; $statement = $connect->prepare($query); $statement->execute(); while($row = $statement->fetch(PDO::FETCH_ASSOC)) { $data[] = $row; } echo json_encode($data); } if($received_data->action == 'insert') { $data = array( ':first_name' => $received_data->firstName, ':last_name' => $received_data->lastName ); $query = " INSERT INTO tbl_sample (first_name, last_name) VALUES (:first_name, :last_name) "; $statement = $connect->prepare($query); $statement->execute($data); $output = array( 'message' => 'Data Inserted' ); echo json_encode($output); } if($received_data->action == 'fetchSingle') { $query = " SELECT * FROM tbl_sample WHERE id = '".$received_data->id."' "; $statement = $connect->prepare($query); $statement->execute(); $result = $statement->fetchAll(); foreach($result as $row) { $data['id'] = $row['id']; $data['first_name'] = $row['first_name']; $data['last_name'] = $row['last_name']; } echo json_encode($data); } if($received_data->action == 'update') { $data = array( ':first_name' => $received_data->firstName, ':last_name' => $received_data->lastName, ':id' => $received_data->hiddenId ); $query = " UPDATE tbl_sample SET first_name = :first_name, last_name = :last_name WHERE id = :id "; $statement = $connect->prepare($query); $statement->execute($data); $output = array( 'message' => 'Data Updated' ); echo json_encode($output); } if($received_data->action == 'delete') { $query = " DELETE FROM tbl_sample WHERE id = '".$received_data->id."' "; $statement = $connect->prepare($query); $statement->execute(); $output = array( 'message' => 'Data Deleted' ); echo json_encode($output); } ?> |