Questions Hub

CRUD operations using Vue.js

Introduction:  In this article, I’ll guide you through the process of effortlessly performing CRUD operations using Vue.js. By following these steps, you’ll seamlessly integrate Vue.js with PHP and efficiently manage data updates in your web applications.

 

CRUD operations 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 Insert Script:

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

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

$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($name!="" &&$email!="" && $message!="" ){
                $sql="INSERT INTO student (name, email, message)VALUES ('$name', '$email', '$message')";
                $run= mysqli_query($link,$sql);
                    if($run){
                        echo "Data Inserted";
                    }
                        else{
                            echo "error";
                        }
                
                } 
    else{
                echo "All fields required !";
            }
mysqli_close($link);
?>

 

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

  1. Create a file named delete.php.
  2. Paste the provided code into delete.php:
<?php  
 //delete.php  
 require "config.php";
 $data = json_decode(file_get_contents("php://input")); 
    
      $id = $data->id;  
      $query = "DELETE FROM student WHERE id='$id'";  
      if(mysqli_query($link, $query))  
      {  
           echo 'Data Deleted';  
      }  
      else  
      {  
           echo 'Error';  
      }    
 ?>

 

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 File:

  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"/>
  
  <!-- Roboto Font Google -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">

  <style>
    body {
      font-family: "Roboto", sans-serif;
      background-color: whitesmoke;
    }
  </style>
  <title>Vue.js CRUD</title>
</head>
<body>

<!-- INSERT DATA FORM -->
<div class="container my-3 bg-white p-5 border rounded" id="app" style="width:760px;">
  <h1 class="text-center">Vue.js CRUD</h1>
  <div class="mb-3">
    <label for="exampleInputName" class="form-label">Name</label>
    <input type="text" class="form-control" v-model="name">
  </div>
  <div class="mb-3">
    <label for="exampleInputEmail" class="form-label">Email Address</label>
    <input type="email" class="form-control" v-model="email">
  </div>
  <div class="mb-3">
    <label for="exampleInputMessage" class="form-label">Your Message</label>
    <textarea class="form-control" rows="3" v-model="message"></textarea>
    <button type="button" class="btn btn-primary mt-3" v-on:click="submitForm">Submit</button>
  </div>
  
  <hr class="my-5"/>

  <!-- DISPLAY DATA HERE -->
  <h2>All Records</h2>
  <table class="table my-3 table-hover">
    <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">
        <td>{{ student.id }}</td>
        <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="updatee(student.id)" 
            data-bs-toggle="modal" data-bs-target="#exampleModal">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-fill" viewBox="0 0 16 16">
              <path d="M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207zm-7.468 7.468A.5.5 0 0 1 6 13.5V13h-.5a.5.5 0 0 1-.5-.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.5-.5V10h-.5a.5.5 0 0 1-.175-.032l-.179.178a.5.5 0 0 0-.11.168l-2 5a.5.5 0 0 0 .65.65l5-2a.5.5 0 0 0 .168-.11z"/>
            </svg>
          </button>
        </td>
        <td>
          <button type="button" class="btn btn-danger btn-sm" v-on:click="deletee(student.id)">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 16">
              <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0z"/>
              <path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z"/>
            </svg>
          </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"><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>

<footer class="d-flex justify-content-center p-5">
  <span class="text-dark">Crafted with love by <a href="https://niyander.com/" class="text-decoration-none">Niyander</a> © 2024 </span>
</footer>

<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 {
        name: null,
        email: null,
        message: null,
        students: [],
        uid: null,
        uname: null,
        uemail: null,
        umessage: null
      }
    },
    mounted() {
      this.fetchData();
    },
    methods: {
      // Insert Data
      submitForm() {
        axios.post('insert.php', {
            name: this.name,
            email: this.email,
            message: this.message
          })
          .then(response => {
            console.log(response.data);
            alert(response.data);
            this.email = null;
            this.message = null;
            this.fetchData();
          })
          .catch(error => {
            console.error(error);
          });
      },
      // Fetch All Data
      fetchData() {
        axios.get('fetch.php')
          .then(response => {
            this.students = response.data;
          })
          .catch(error => {
            console.error('Error fetching data:', error);
          });
      },
      // Delete Single Data
      deletee(id) {
        if (confirm("Would you like to delete this data?")) {
          axios.post('delete.php', { id: id })
            .then(response => {
              console.log(response.data);
              this.fetchData();
            })
            .catch(error => {
              console.error('Error deleting data:', error);
            });
        } else {
          console.log("Deletion canceled!");
        }
      },
      // Update Data
      updatee(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
      updateStudent() {
        axios.post('update.php', {
            id: this.uid,
            name: this.uname,
            email: this.uemail,
            message: this.umessage
          })
          .then(response => {
            console.log(response.data);
            this.fetchData();
          })
          .catch(error => {
            console.error('Error updating data:', error);
          });
      }
    }
  });
  app.mount('#app');
</script>

</body>
</html>

 

Conclusion:

By following these steps, you’ve learned how to effortlessly performing CRUD operations using Vue.js. Implementing this approach will enable you to efficiently manage data in your web applications.