Questions Hub

Update Data in PHP using Vue.js

Introduction:  In this article, I’ll guide you through the process of effortlessly updating 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 updates in your web applications.

 

Update 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 Update Script:

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

$data = json_decode(file_get_contents("php://input"));

$id = mysqli_real_escape_string($link, $data->id);
$name = mysqli_real_escape_string($link, $data->name);
$email = mysqli_real_escape_string($link, $data->email);
$message = mysqli_real_escape_string($link, $data->message);

if($id!="" && $name!="" && $email!="" && $message!="" ){
    $sql="UPDATE `student` SET `name`='$name',`email`='$email',`message`= '$message' WHERE id = '$id'"; 
    
    $datc= mysqli_query($link,$sql);
        if($datc){
            echo "Data Updated";
        }
        else{
            echo "error";
        }
}else{
    echo "All fields Required !";
}
    
mysqli_close($link);
?>

 

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;">

<!-- 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>



<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Update Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
     <div class="modal-body card">
    Id <input type="text" class="form-control" v-model="uid" disabled><br/>
    Name <input type="text" class="form-control" v-model="uname" disabled><br/>
    Email <input type="text" class="form-control" v-model="uemail"><br/>
    Message <input type="text" class="form-control"  v-model="umessage"><br/>
    <button type="button" class="btn btn-primary" v-on:click="updateStudent" data-bs-dismiss="modal" aria-label="Close" >Save changes</button>
</div>
      </div>
    </div>
  </div>
</div>

</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: [],
        
        uid: null,
        uname: null,
        uemail: null,
        umessage: null
      }
    },
    mounted() {
      this.fetchData();
    },
    methods: {
//** Fetch All Data **//
      fetchData() {
        axios.get('fetch.php')
          .then(response => {
            this.students = response.data;
          })
          .catch(error => {
            console.error('Error fetching data:', error);
          });
      },

      
//** Update function here **//  
      
update(id) {
  // Find the student record with the given id
  const student = this.students.find(student => student.id === id);
  if (student) {
    this.uid = student.id;
    this.uname = student.name;
    this.uemail = student.email;
    this.umessage = student.message;
  }
},

/* update field data put on database function here */	
    updateStudent() {
    axios.post('update.php', {
      id: this.uid,
      email: this.uemail,
      message: this.umessage
    })
    .then(response => {
      console.log(response.data);
      this.fetchData(); // Refresh student records
    })
    .catch(error => {
      console.error('Error updating data:', error);
    });
        
   }
   
}

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

 

Conclusion:

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