Read From Database and Add It in Vuejs
Add, edit, and delete functionality mostly requires on every dynamic based web projection.
With AJAX you can improve user experience and practise these operations without page reload.
For this, I am using the Axios packet.
In this tutorial, I show how you can select, insert, update, and delete records from MySQL database with Vue.js and PHP.
Contents
- Tabular array construction
- Configuration
- Download & Include
- HTML
- PHP
- Script
- Decision
1. Table structure
I am using users table in the example.
CREATE Tabular array `users` ( `id` int(eleven) Not Cypher Primary Central AUTO_INCREMENT, `username` varchar(100) NOT Cypher, `name` varchar(100) NOT Zilch, `email` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Configuration
Create a new config.php file for the database configuration.
Completed Lawmaking
<?php $host = "localhost"; /* Host name */ $user = "root"; /* User */ $password = ""; /* Password */ $dbname = "tutorial"; /* Database name */ $con = mysqli_connect($host, $user, $password,$dbname); // Check connexion if (!$con) { die("Connection failed: " . mysqli_connect_error()); } 3. Download & Include
- Download Axios package from GitHub. or you tin can as well use CDN (https://unpkg.com/axios/dist/axios.min.js).
- Now, include
axios.min.jswithvue.jsin the<head>section.
<script src="vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
4. HTML
Create <table> to list and add records.
Add together –
Created 3 textboxes and a button in the columns. Added @click='addRecord()' in the button.
Update/Delete –
Use five-for='(user,index) in users' to add together new rows. Create text boxes to edit values and with 5-model brandish value.
Create ii buttons for Update and Delete record.
In the update button added @click='updateRecord(alphabetize,user.id)' and in the delete push button added @click='deleteRecord(index,user.id)'.
Completed Code
<div id='myapp'> <table border='1' width='80%' fashion='border-collapse: collapse;'> <tr> <thursday>Username</thursday> <thursday>Name</th> <th>Email</th> <th></thursday> </tr> <!-- Add together --> <tr> <td><input type='text' 5-model='username'></td> <td><input type='text' v-model='proper noun'></td> <td><input blazon='text' five-model='email'></td> <td><input type='button' value='Add' @click='addRecord();'></td> </tr> <!-- Update/Delete --> <tr v-for='(user,index) in users'> <td><input type='text' v-model='user.username' ></td> <td><input type='text' v-model='user.name' ></td> <td><input type='text' five-model='user.email' ></td> <td><input type='push button' value='Update' @click='updateRecord(index,user.id);'> <input type='push button' value='Delete' @click='deleteRecord(index,user.id)'></td> </tr> </table> </div>
v. PHP
Create a new ajaxfile.php.
From this page handle iv requests –
- $request == 1 – Fetch records from the
userstable and initialize$responsearray. Return JSON response. - $request == 2 – Check username already exists or not. If not then insert record.
- $request == 3 – Update tape in the
userstable co-ordinate to id. - $request == four – Delete record from the
userstable according to id.
Completed Code
<?php include "config.php"; $data = json_decode(file_get_contents("php://input")); $asking = $data->request; // Fetch All records if($request == 1){ $userData = mysqli_query($con,"select * from users order by id desc"); $response = array(); while($row = mysqli_fetch_assoc($userData)){ $response[] = $row; } repeat json_encode($response); exit; } // Add together record if($request == 2){ $username = $information->username; $name = $data->name; $email = $information->electronic mail; $userData = mysqli_query($con,"SELECT * FROM users WHERE username='".$username."'"); if(mysqli_num_rows($userData) == 0){ mysqli_query($con,"INSERT INTO users(username,name,email) VALUES('".$username."','".$proper name."','".$email."')"); echo "Insert successfully"; }else{ echo "Username already exists."; } leave; } // Update tape if($request == 3){ $id = $data->id; $name = $data->proper noun; $email = $data->email; mysqli_query($con,"UPDATE users Gear up name='".$name."',e-mail='".$email."' WHERE id=".$id); echo "Update successfully"; exit; } // Delete tape if($request == iv){ $id = $data->id; mysqli_query($con,"DELETE FROM users WHERE id=".$id); echo "Delete successfully"; go out; } half-dozen. Script
Ascertain five variable – users, username, name, and email.
Create 4 methods –
- allRecords – Transport Mail request to fetch records where pass
request: 1. On successful callback assignresponse.datatoapp.users. - addRecord – Send POST request to add new record where laissez passer
request: two, username: this.username, name: this.name, e-mail: this.email. On successful callback Empty the data values and callallRecordsmethods. - updateRecord – Read proper noun and email from
usersco-ordinate to index and ship a POST request to update record where laissez passerrequest: three, id: id, name: name, email: electronic mail. - deleteRecord – Send POST request to delete record where pass
request: iv, id: id. On successful callback remove an index fromusersusingsplice().
Also, define created option to call allRecords() method on after instance is been created.
Completed Code
var app = new Vue({ el: '#myapp', data: { users: "", username: "", proper name: "", electronic mail: "" }, methods: { allRecords: function(){ axios.mail service('ajaxfile.php', { request: one }) .then(function (response) { app.users = response.data; }) .catch(function (mistake) { panel.log(error); }); }, addRecord: role(){ if(this.username != '' && this.proper name != '' && this.email != ''){ axios.post('ajaxfile.php', { request: 2, username: this.username, proper noun: this.proper noun, email: this.e-mail }) .then(function (response) { // Fetch records app.allRecords(); // Empty values app.username = ''; app.name = ''; app.email = ''; alert(response.data); }) .catch(function (error) { console.log(error); }); }else{ alert('Fill all fields.'); } }, updateRecord: function(alphabetize,id){ // Read value from Textbox var name = this.users[alphabetize].name; var email = this.users[index].email; if(name !='' && email !=''){ axios.postal service('ajaxfile.php', { request: three, id: id, proper noun: name, e-mail: electronic mail }) .then(function (response) { alert(response.information); }) .catch(function (error) { console.log(error); }); } }, deleteRecord: role(index,id){ axios.postal service('ajaxfile.php', { asking: iv, id: id }) .then(function (response) { // Remove index from users app.users.splice(index, 1); alert(response.information); }) .catch(function (error) { console.log(mistake); }); } }, created: function(){ this.allRecords(); } }) 7. Decision
Utilize the index to select the specific tape from an Assortment for the update or delete and with created option load records when the case initialized.
If yous establish this tutorial helpful so don't forget to share.
Are yous want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.
Related posts:
Source: https://makitweb.com/insert-update-delete-records-from-mysql-with-vue-js/
0 Response to "Read From Database and Add It in Vuejs"
Postar um comentário