vue 리스트 게시판 모습
새로운 사용자를 추가시 모달창을 불러온다.
DB저장 성공시 뜨는 메세지.(오류 메세지로 출력가능)

 

수정시 모달창이 뜨면서 수정 가능
성공시 뜨는 메세지(오류 메세지도 출력가능)
유저 삭제시 뜨는 모달창
성공시 뜨는 메시지(오류도 출력가능)

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>


    <!-- CSS only -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous" />
    <script src="https://kit.fontawesome.com/42e2ecb8e0.js" crossorigin="anonymous"></script>
    <style type="text/css">
        #overlay {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0, 0, 0, 0.6);
        }
    </style>

</head>

<body>
    <!-- header -->
    <div id="app">
        <div class="container-fluid">
            <div class="row bg-dark">
                <div class="col-lg-12">
                    <p class="text-center text-light display-4 pt-2" style="font-size: 25px">
                        CRUD 어플리케이션 vue, PHP, mysqli
                    </p>
                </div>
            </div>
        </div>
        <div class="container">
            <div class="row mt-3">
                <div class="col-lg-6">
                    <h3 class="text-info">등록 된 유저들</h3>
                </div>
                <div class="col-lg-6">
                    <button class="btn btn-info float-right" @click="showAddModal=true">
              <i class="fas fa-user"></i> &nbsp;  &nbsp; 새롭게 추가
            </button>
                </div>
            </div>
            <hr class="bg-info" />
            <div class="alert alert-danger" v-if="errorMsg">{{ errorMsg }}</div>
            <div class="alert alert-success" v-if="successMsg">{{ successMsg }} </div>

            <!--디스플레이 레코드-->
            <div class="row">
                <div class="col-lg-12">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr class="text-center bg-info text-light">
                                <th>ID</th>
                                <th>이름</th>
                                <th>이메일</th>
                                <th>핸드폰</th>
                                <th>수정</th>
                                <th>삭제</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="text-center" v-for="user in users">
                                <td>{{ user.id }}</td>
                                <td>{{ user.name }}</td>
                                <td>{{ user.email }}</td>
                                <td>{{ user.phone }}</td>
                                <td>
                                    <a href="#" class="text-success" @click="showEditModal=true; selectUser(user);"><i class="fas fa-edit"></i></a>
                                </td>
                                <td>
                                    <a href="#" class="text-danger" @click="showDeleteModal=true; selectUser(user);"><i class="fas fa-trash-alt"></i></a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!--새로운 사용자 추가 모달-->
        <div id="overlay" v-if="showAddModal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">새로운 사용자 추가</h5>
                        <button type="button" class="close" @click="showAddModal=false">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body p-4">
                        <form action="#" method="post">
                            <div class="form-group">
                                <input type="text" name="name" class="form-control form-control-lg" placeholder="name" v-model="newUser.name">
                            </div>
                            <div class="form-group">
                                <input type="text" name="email" class="form-control form-control-lg" placeholder="email" v-model="newUser.email">
                            </div>
                            <div class="form-group">
                                <input type="text" name="phone" class="form-control form-control-lg" placeholder="phone" v-model="newUser.phone">
                            </div>
                            <div class="form-group">
                                <button class="btn btn-info btn-block btn-lg" @click="showAddModal=false; addUser(); clearMsg();">사용자 추가</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!--사용자 수정 모달-->
        <div id="overlay" v-if="showEditModal ">
            <div class="modal-dialog ">
                <div class="modal-content ">
                    <div class="modal-header ">
                        <h5 class="modal-title ">사용자 수정</h5>
                        <button type="button " class="close " @click="showEditModal=false ">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body p-4 ">
                        <form action="# " method="post ">
                            <div class="form-group ">
                                <input type="text " name="name " class="form-control form-control-lg" v-model="currentUser.name">
                            </div>
                            <div class="form-group ">
                                <input type="text " name="email " class="form-control form-control-lg" placeholder="이메일" v-model="currentUser.email">
                            </div>
                            <div class="form-group ">
                                <input type="text " name="phone " class="form-control form-control-lg" placeholder="핸드폰" v-model="currentUser.phone">
                            </div>
                            <div class="form-group ">
                                <button class="btn btn-info btn-block btn-lg " @click="showEditModal=false; updateUser(); clearMsg();">사용자 업데이트</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!--사용자 삭제 모달-->
        <div id="overlay" v-if="showDeleteModal ">
            <div class="modal-dialog ">
                <div class="modal-content ">
                    <div class="modal-header ">
                        <h5 class="modal-title ">사용자 삭제</h5>
                        <button type="button " class="close " @click="showDeleteModal=false ">
                            <span aria-hidden="true ">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body p-4 ">
                        <h4 class="text-danger ">정말 삭제하시겠습니까?</h4>
                        <h5>당신은 '{{ currentUser.name }}'를 삭제합니다.</h5>
                        <hr>
                        <button class="btn btn-danger btn-lg " @click="showDeleteModal=false; deleteUser(); clearMsg(); ">네</button> &nbsp;&nbsp;&nbsp;&nbsp;
                        <button class="btn btn-success btn-lg " @click="showDeleteModal=false ">아니오</button>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js "></script>
    <script src="https://cdn.jsdelivr.net/npm/vue "></script>
    <script>
        var app = new Vue({
            el: "#app ",
            data: {
                errorMsg: "",
                successMsg: "",
                showAddModal: false,
                showEditModal: false,
                showDeleteModal: false,
                users: [],
                newUser: {
                    name: "",
                    email: "",
                    phone: ""
                },
                currentUser: {}
            },

            mounted: function() {
                this.getAllUsers();
            },
            methods: {

                getAllUsers() {
                    axios.get("http://localhost/crud-vue-php/process.php?action=read").then(function(response) {
                        if (response.data.error) {
                            app.errorMsg = response.data.message;
                        } else {
                            app.users = response.data.users;
                        }
                    });
                },

                addUser() {
                    var formData = app.toFormData(app.newUser);
                    axios.post("http://localhost/crud-vue-php/process.php?action=create", formData).then(function(response) {
                        app.newUser = {
                            name: "",
                            email: "",
                            phone: ""
                        };
                        if (response.data.error) {
                            app.errorMsg = response.data.message;
                        } else {
                            app.successMsg = response.data.message;
                            app.getAllUsers();
                        }
                    });
                },

                updateUser() {
                    var formData = app.toFormData(app.currentUser);
                    axios.post("http://localhost/crud-vue-php/process.php?action=update", formData).then(function(response) {
                        app.currentUser = {};
                        if (response.data.error) {
                            app.errorMsg = response.data.message;
                        } else {
                            app.successMsg = response.data.message;
                            app.getAllUsers();
                        }
                    });
                },

                deleteUser() {
                    var formData = app.toFormData(app.currentUser);
                    axios.post("http://localhost/crud-vue-php/process.php?action=delete", formData).then(function(response) {
                        app.currentUser = {};
                        if (response.data.error) {
                            app.errorMsg = response.data.message;
                        } else {
                            app.successMsg = response.data.message;
                            app.getAllUsers();
                        }
                    });
                },

                toFormData(obj) {
                    var fd = new FormData();
                    for (var i in obj) {
                        fd.append(i, obj[i]);
                    }
                    return fd;
                },
                selectUser(user) {
                    app.currentUser = user;
                },
                clearMsg() {
                    app.errorMsg = "";
                    app.successMsg = "";
                }


            }
        });
    </script>
</body>

</html>

process.php

<?php
    $conn = new mysqli("localhost", "root", "", "crud_vue");
    if($conn->connect_error){
        die("Connection Failed!".$conn->connect_error);
    }
    //echo("Success");
    $result = array('error'=>false);
    $action = '';


    if(isset($_GET['action'])){
        $action = $_GET['action'];
    }



    if($action == 'read'){
        $sql = $conn->query("SELECT * FROM users");
        $users = array();
        while($row = $sql->fetch_assoc()){
            array_push($users, $row);
        }
        $result['users'] = $users;
    }


    if($action == 'create'){
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];

        $sql = $conn->query("INSERT INTO users (name,email,phone) VALUES('$name','$email','$phone')");
        
        if($sql){
            $result['message'] = "user added successfully!";
        }
        else{
            $result['error'] = true;
            $result['message'] = "failed to add user!";
        }
    }


    if($action == 'update'){
        $id = $_POST['id'];
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];

        $sql = $conn->query("UPDATE users SET name='$name', email='$email', phone='$phone' WHERE id='$id'");

        if($sql){
            $result['message'] = "user update successfully";
        }
        else{
            $result['error'] = true;
            $result['message'] = "failed to update user!";
        }
    }


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

        $sql = $conn->query("DELETE FROM users WHERE id='$id'");

        if($sql){
            $result['message'] = "유저 삭제 성공했다!";
        }
        else{
            $result['error'] = true;
            $result['message'] = "유저 삭제 실패 ㅠㅠ!";
        }
    }

    $conn->close();
    echo json_encode($result);
    
?>

+ Recent posts