article

Tuesday, February 1, 2022

Vuejs PHP OOP PDO Mysql CRUD (Create, Read, Update and Delete)

Vuejs PHP OOP PDO Mysql CRUD (Create, Read, Update and Delete)

Bootstrap 5.1 Version
https://getbootstrap.com/docs/5.1/getting-started/introduction/

https://bootstrap-vue.org/

https://bootstrap-vue.org/docs/components/modal#modals

https://vuejs.org/v2/guide/

CREATE TABLE `vueuser` (
  `id` int(11) NOT NULL,
  `name` varchar(30) NOT NULL,
  `email` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `vueuser` (`id`, `name`, `email`) VALUES
(1, 'cairocoders', 'cairocoders@gmail.com'),
(2, 'tutorial101.blogspot.com', 'tutorial101@gmail.com'),
(3, 'Ashton Cox', 'AshtonCox@gmail.com'),
(4, 'Bradley Greer', 'BradleyGreer@gmail.com'),
(5, 'Clydey Ednalan', 'clydeyednalan@gmail.com');

ALTER TABLE `vueuser`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `vueuser`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
index.php
//index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<title>Vuejs PHP OOP PDO Mysql CRUD (Create, Read, Update and Delete)</title>
<style>
[v-cloak] {
    display: none;
}
</style>
</head>
<body class="bg-light">
    <div class="container" id="app" v-cloak>
        <div class="row">
            <div class="col-md-10"><h3>Vuejs PHP OOP PDO Mysql CRUD (Create, Read, Update and Delete)</h3>
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex d-flex justify-content-between">
                            <div class="lead">PHP PDO VUEJS CRUD</div>
                            <button id="show-btn" @click="showModal('my-modal')" class="btn btn-primary">Add Records</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="text-muted lead text-center" v-if="!records.length">No record found</div>
                        <div class="table table-success table-striped" v-if="records.length">
                            <table class="table table-borderless">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Email</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="(record, i) in records" :key="record.id">
                                        <td>{{i + 1}}</td>
                                        <td>{{record.name}}</td>
                                        <td>{{record.email}}</td>
                                        <td>
                                            <a href="#" @click.prevent="deleteRecord(record.id)" class="btn btn-danger">Delete</a>
                                            <a href="#" @click.prevent="editRecord(record.id)" class="btn btn-primary">Edit</a>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Add Records Modal -->
                <b-modal ref="my-modal" hide-footer title="Add Records">
					<form action="" @submit.prevent="onSubmit">
                        <div class="form-group">
                            <label for="">Name</label>
                            <input type="text" v-model="name" class="form-control">
                        </div>
                        <div class="form-group">
                            <label for="">Email</label>
                            <input type="email" v-model="email" class="form-control">
                        </div>
                        <div class="form-group">
							<button class="btn btn-sm btn-outline-info">Add Records</button>
                        </div>
                    </form>
                    <b-button class="mt-3" variant="outline-danger" block @click="hideModal('my-modal')">Close Me</b-button>
                </b-modal>
						
                <!-- Update Record Modal -->
                <div>
                    <b-modal ref="my-modal1" hide-footer title="Update Record">
                        <div>
                            <form action="" @submit.prevent="onUpdate">
                                <div class="form-group">
                                    <label for="">Name</label>
                                    <input type="text" v-model="edit_name" class="form-control">
                                </div>
                                <div class="form-group">
                                    <label for="">Email</label>
                                    <input type="email" v-model="edit_email" class="form-control">
                                </div>
                                <div class="form-group">
                                    <button class="btn btn-sm btn-outline-info">Update Record</button>
                                </div>
                            </form>
                        </div>
                        <b-button class="mt-3" variant="outline-danger" block @click="hideModal('my-modal1')">Close Me</b-button>
                    </b-modal>
                </div>
            </div>
        </div>

    </div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<!-- BootstrapVue js -->
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<!-- Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
app.js
//app.js
var app = new Vue({
    el: "#app",
    data: {
        name: "",
        email: "",
        records: [],
        edit_id: "",
        edit_name: "",
        edit_email: "",
    },

    methods: {
        showModal(id) {
            this.$refs[id].show();
        },
        hideModal(id) {
            this.$refs[id].hide();
        },

        onSubmit() {
            if (this.name !== "" && this.email !== "") {
                var fd = new FormData();

                fd.append("name", this.name);
                fd.append("email", this.email);

                axios({
                    url: "insert.php",
                    method: "post",
                    data: fd,
                })
                    .then((res) => {
                        if (res.data.res == "success") {
                            app.makeToast("Success", "Record Added", "default");

                            this.name = "";
                            this.email = "";

                            app.hideModal("my-modal");
                            app.getRecords();
                        } else {
                            app.makeToast("Error", "Failed to add record. Please try again", "default");
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            } else {
                alert("All field are required");
            }
        },

        getRecords() {
            axios({
                url: "records.php",
                method: "get",
            })
                .then((res) => {
                    this.records = res.data.rows;
                })
                .catch((err) => {
                    console.log(err);
                });
        },

        deleteRecord(id) {
            if (window.confirm("Delete this record")) {
                var fd = new FormData();

                fd.append("id", id);

                axios({
                    url: "delete.php",
                    method: "post",
                    data: fd,
                })
                    .then((res) => {
                        if (res.data.res == "success") {
                            app.makeToast("Success", "Record delete successfully", "default");
                            app.getRecords();
                        } else {
                            app.makeToast("Error", "Failed to delete record. Please try again", "default");
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }
        },

        editRecord(id) {
            var fd = new FormData();

            fd.append("id", id);

            axios({
                url: "edit.php",
                method: "post",
                data: fd,
            })
                .then((res) => {
                    if (res.data.res == "success") {
                        this.edit_id = res.data.row[0];
                        this.edit_name = res.data.row[1];
                        this.edit_email = res.data.row[2];
                        app.showModal("my-modal1");
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },

        onUpdate() {
            if (
                this.edit_name !== "" &&
                this.edit_email !== "" &&
                this.edit_id !== ""
            ) {
                var fd = new FormData();

                fd.append("id", this.edit_id);
                fd.append("name", this.edit_name);
                fd.append("email", this.edit_email);

                axios({
                    url: "update.php",
                    method: "post",
                    data: fd,
                })
                    .then((res) => {
                        if (res.data.res == "success") {
                            app.makeToast("Sucess", "Record update successfully", "default");

                            this.edit_name = "";
                            this.edit_email = "";
                            this.edit_id = "";

                            app.hideModal("my-modal1");
                            app.getRecords();
                        }
                    })
                    .catch((err) => {
                        app.makeToast("Error", "Failed to update record", "default");
                    });
            } else {
                alert("All field are required");
            }
        },

        makeToast(vNodesTitle, vNodesMsg, variant) {
            this.$bvToast.toast([vNodesMsg], {
                title: [vNodesTitle],
                variant: variant,
                autoHideDelay: 1000,
                solid: true,
            });
        },
    },

    mounted: function () {
        this.getRecords();
    },
});
model.php
//model.php
<?php
class Model
{
	private $server = 'localhost';
	private $username = 'root';
	private $password = '';
	private $db = 'testingdb';
	private $conn;

	public function __construct()
	{
		try {
			$this->conn = new PDO("mysql:host=$this->server;dbname=$this->db", $this->username, $this->password);
		} catch (PDOException $e) {
			echo "Connection failed: " . $e->getMessage();
		}
	}

	public function store($name, $email)
	{
		$stmt = $this->conn->prepare("INSERT INTO `vueuser` (`name`, `email`) VALUES ('$name', '$email')");
		if ($stmt->execute()) {
			return true;
		} else {
			return;
		}
	}

	public function findAll()
	{
		$data = [];

		$stmt = $this->conn->prepare("SELECT * FROM `vueuser` ORDER BY `id` ASC");
		if ($stmt->execute()) {
			$data = $stmt->fetchAll();
		}

		return $data;
	}

	public function destroy($id)
	{
		$stmt = $this->conn->prepare("DELETE FROM `vueuser` WHERE `id` = '$id'");
		if ($stmt->execute()) {
			return true;
		} else {
			return;
		}
	}

	public function findOne($id)
	{
		$data = [];

		$stmt = $this->conn->prepare("SELECT * FROM `vueuser` WHERE `id` = '$id'");
		if ($stmt->execute()) {
			$data = $stmt->fetch();
		}

		return $data;
	}

	public function update($id, $name, $email)
	{
		$stmt = $this->conn->prepare("UPDATE `vueuser` SET `name` = '$name', `email` = '$email' WHERE `id` = '$id'");
		if ($stmt->execute()) {
			return true;
		} else {
			return;
		}
	}
}
records.php
//records.php
<?php 
	include 'model.php';

	$model = new Model();

	$rows = $model->findAll();

	$data = array('rows' => $rows);

	echo json_encode($data);
insert.php
//insert.php
<?php 
	if (isset($_POST['name']) && isset($_POST['email'])) {
		$name = $_POST['name'];
		$email = $_POST['email'];

		include 'model.php';

		$model = new Model();

		if ($model->store($name, $email)) {
			$data = array('res' => 'success');
		}else{
			$data = array('res' => 'error');
		}

		echo json_encode($data);
	}
edit.php
//edit.php
<?php 
	if (isset($_POST['id'])) {
		$id = $_POST['id'];

		include 'model.php';

		$model = new Model();

		if ($row = $model->findOne($id)) {
			$data = array('res' => 'success', 'row' => $row);
		}else{
			$data = array('res' => 'error');
		}

		echo json_encode($data);
	}
update.php
//update.php
<?php 
	if (isset($_POST['id']) && isset($_POST['name']) && isset($_POST['email'])) {
		
		$id = $_POST['id'];
		$name = $_POST['name'];
		$email = $_POST['email'];

		include 'model.php';

		$model = new Model();

		if ($model->update($id, $name, $email)) {
			$data = array('res' => 'success');
		}else{
			$data = array('res' => 'error');
		}

		echo json_encode($data);
	}
 ?>
 
delete.php
//delete.php
<?php 

	if (isset($_POST['id'])) {
		$id = $_POST['id'];

		include 'model.php';

		$model = new Model();

		if ($model->destroy($id)) {
			$data = array('res' => 'success');
		}else{
			$data = array('res' => 'error');
		}

		echo json_encode($data);
	}

Related Post