Create CRUD(create,read,update,delete) in PHP

min read

Day 4 #100DaysOfCode
Trong ngày thứ 4 hôm nay mình thực hiện một chức năng CRUD(create,read,update,delete) trong PHP, nay mình làm với ví dụ mà thầy cô, kêu về nhà thực hiện, để chuẩn bị cho buổi thực hành kế tiếp vào chiều nay

Đầu tiên máy tính mình đã cài đặt sẵn phần mềm Xampp, để có thể kết nối tới localhost/phpmyadmin, sau đó tạo database chứa cở sở dữ liệu. Ở đây mình tạo một table "posts" gồm những thông tin dữ liệu như: idPost,Title,Body,Slug

Các bạn nhìn thấy bên trên mình có table "posts" và insert 2 record mẫu để hồi hiển thị dữ liệu ra

Tiếp tục mình vào thư mục htdocs, tạo thư mục project "posts" chưa các file sau : 

+ define.php : dùng cấu hình các biến kết nối dữ liệu

+ index.php :  dùng cài đặt giao diện hiển thị chung cho các chức năng

+ home.php : dùng hiển thị dữ liệu posts , "Read"

+ edit.php : dùng cài đặt chỉnh sửa dữ liệu post "Update"

+ add.php : dùng thêm dữ liệu post "Add"

+ delete.php :  dùng xóa dữ liệu post "Delete"

Okay, bên trên là những file mình cần tạo, giờ mình sẽ đi sâu vào từng file

File define.php

<?php
   /* config localhost */
    define("LOCALHOST","localhost");
    /* database name */
    define("DATABASE","admin_demo");
    /* username */
    define("USERNAME","root");
    /* password */
    define("PASSWORD","");
?>

Đoạn code trong file define.php trên chúng ta chỉ cài đặt thiếp lập các biến kết nối dữ liệu, để sao này chúng ta có thể dễ dàng sửa chữa nó

+ File index.php

<?php
    require_once "define.php";
    $conn = new mysqli(LOCALHOST,USERNAME,PASSWORD,DATABASE);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Posts</title>
    <style>
        *{margin:0;padding:0;}
        
        header{
            width:100%;
            background:rgba(0,145,234,1);
            padding:20px 0px;
        }
        .box_posts{
            width:1000px;
            margin:30px auto;
        }
        table, td, th {
            border: 1px solid black;
            padding:10px;
            box-sizing:border-box;
        }

       a{
           text-decoration:none;
       }
        table {
            border-collapse: collapse;
        }
        span{
            padding: 5px 10px;
            box-sizing: border-box;
            
            color: #fff;
            font-size: 13px;
            border-radius: 5px;
        }
        .edit{
            background: #0d6efd;
        }
        .delete{
            background:#dc3545;
        }
        .add{
            width: 100px;
            display: block;
            padding: 5px;
            text-align: center;
            box-sizing: border-box;
            color: #fff;
          
            background: #198754;
            margin-bottom: 7px;
            border-radius: 5px;
            font-weight: bold;
            font-size: 14px;
        }
      
    </style>
</head>
<body>
    <header></header>
    <div class="box_posts">
     
        <?php
            $page = "home";
            if(isset($_GET["page"]) && $_GET["page"]!=""){
                $page=$_GET["page"];
            }
            switch($page){
                case "home":include "home.php";break;
                case "delete":include "delete.php";break;
                case "edit":include "edit.php";break;
                case "add":include "add.php";break;
                default :
                  include "home.php";
                  break;
            }

        ?>
    </div>
</body>
</html>

Trong đoạn code index.php bạn vừa nhìn thấy bên trên, để chung ta có thể kết nối được với MYSQL của ta , chúng ta cần khai báo đoạn mã sau

<?php
    require_once "define.php";
    $conn = new mysqli(LOCALHOST,USERNAME,PASSWORD,DATABASE);

?>

Bên cạnh đó bạn nhìn xuống bên dưới mình có code một switch để kiểm tra xem thao khác người dùng đang ở chức năng nào? 

Ví dụ: ?page=home , thì nó sẽ include "home.php" , còn nếu ?page=edit nó sẽ incldue "edit.php", để làm được điều đó bạn cần khai báo như đoạn code bên dưới đây

 <?php
            $page = "home";
            if(isset($_GET["page"]) && $_GET["page"]!=""){
                $page=$_GET["page"];
            }
            switch($page){
                case "home":include "home.php";break;
                case "delete":include "delete.php";break;
                case "edit":include "edit.php";break;
                case "add":include "add.php";break;
                default :
                  include "home.php";
                  break;
            }

        ?>

+ File Home.php 

        <a href="?page=add" class="add">Add Post</a>
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Body</th>
                    <th>Slug</th>
                    <th>Modify</th>
                    <th>Remove</th>
                </tr>
            </thead>
            <tbody>
                <?php
                
                    /* SQL SELECT POSTS */
                    $sql = "SELECT * FROM `POSTS` ORDER BY `idPost` DESC";
                    $result = mysqli_query($conn , $sql);

                    $str = "";
                    while($row = mysqli_fetch_assoc($result)){
                        $str.="<tr>";
                            $str.="<td>".$row['idPost']."</td>";
                            $str.="<td>".$row['Title']."</td>";
                            $str.="<td>".$row['Body']."</td>";
                            $str.="<td>".$row['Slug']."</td>";
                            $str.="<td><a href='?page=edit&id=".$row['idPost']."'><span class='edit'>Edit</span></a></td>";
                            $str.="<td><a href='?page=delete&id=".$row['idPost']."'><span class='delete'>Delete</span></a></td>";
                        $str.="</tr>";
                    }
                    echo $str;

                ?>
            </tbody>
        </table>

Trong đoạn mã trên ta cần hiển thị dữ liệu table "posts" ra , ta cần viết câu lệnh truy vấn như sau: 

 $sql = "SELECT * FROM `POSTS` ORDER BY `idPost` DESC";
 $result = mysqli_query($conn , $sql);

Sau khi truy vấn xong ta cần while dữ liệu ra như sau:

$str = "";
                    while($row = mysqli_fetch_assoc($result)){
                        $str.="<tr>";
                            $str.="<td>".$row['idPost']."</td>";
                            $str.="<td>".$row['Title']."</td>";
                            $str.="<td>".$row['Body']."</td>";
                            $str.="<td>".$row['Slug']."</td>";
                            $str.="<td><a href='?page=edit&id=".$row['idPost']."'><span class='edit'>Edit</span></a></td>";
                            $str.="<td><a href='?page=delete&id=".$row['idPost']."'><span class='delete'>Delete</span></a></td>";
                        $str.="</tr>";
                    }
                    echo $str;

+ File add.php : ?page=add


<?php
/* SET SUBMIT ADD POST */
if(isset($_POST["submit"])){
    if($_POST['Title'] !="" && $_POST["Body"]!="" && $_POST["Slug"]!=""){
        $sql_insert = "INSERT INTO `posts`(`Title`,`Body`,`Slug`) VALUES('".$_POST["Title"]."','".$_POST["Body"]."','".$_POST["Slug"]."')";
        $query = mysqli_query($conn,$sql_insert);
        if($query){
           $last_id = mysqli_insert_id($conn);
           header("Location:?page=home");
        }
    }
}

?>
<div class="box_edit">
<form action="" method="post">
    <h2>Add Post</h2>
    <div class="form-item">
        <label>Title</label>
        <input type="text" name="Title" placeholder="Title"/>
    </div>
    <div class="form-item">
        <label>Slug</label>
        <input type="text" name="Slug" placeholder="Slug" />
    </div>
    <div class="form-item">
        <label>Body</label>
        <textarea cols="20" rows="5" name="Body" placeholder="Body"></textarea>
    </div>
   
    <div class="form-item">
        <input type="submit" name="submit" value="Submit" />
    </div>
</form>
</div>
<style>
.box_edit{
    width:600px;
    margin:auto;
}
h2{
    font-size:23px;
    padding:5px;
    border-bottom:2px solid rgba(0,145,234,1);
    position:relative;
    z-index:1000;
    text-indent:10px;
    overflow: hidden;
    color:#fff;
    margin-bottom:10px;
}
h2::before{
    content: "";
    width: 200px;
    height: 100%;
    background: rgba(0,145,234,1);
    position: absolute;
    top: 0;
    left: -37px;
    z-index: -1;
    transform: skewX(30deg);
   
}
.form-item{
   margin-bottom:10px;
}
label{
    font-size:20px;
    display:block;
    font-weight:bold;
}
input,textarea{
    width:100%;
    padding:10px;
    box-sizing:border-box;
    border:none;
    box-shadow:0 0 1px  #000;
    outline:none;

}
input[type="submit"]{
    background: #000;
    color:#fff;
    font-weight:bold;
}

</style>

Đoạn code trên ta cần cài đặt một giao diện Form Html để người dùng thao tác thêm dữ liệu, với đoạn code dưới đây khi người dùng bấm submit form thì dữ liệu sẽ được kiểm tra và thêm vào database

<?php
/* SET SUBMIT ADD POST */
if(isset($_POST["submit"])){
    if($_POST['Title'] !="" && $_POST["Body"]!="" && $_POST["Slug"]!=""){
        $sql_insert = "INSERT INTO `posts`(`Title`,`Body`,`Slug`) VALUES('".$_POST["Title"]."','".$_POST["Body"]."','".$_POST["Slug"]."')";
        $query = mysqli_query($conn,$sql_insert);
        if($query){
           $last_id = mysqli_insert_id($conn);
           header("Location:?page=home");
        }
    }
}

?>

+ File edit.php : ví dụ?page=edit&id=2


<?php

    $idPost = $_GET["id"];
    $sql_edit = "SELECT * FROM `posts` WHERE `posts`.`idPost`=".$idPost;
    $result = mysqli_query($conn,$sql_edit);
    if(mysqli_num_rows($result)>0){
        $post = mysqli_fetch_assoc($result);  
    }else{

        echo "<script>alert('idPost không tồn tại');</script>";

        echo "<script>window.location.href='?page=home';</script>";
    }

    /* SET SUBMIT EDIT */
    if(isset($_POST["submit"])){
        if($_POST['Title'] !="" && $_POST["Body"]!="" && $_POST["Slug"]!=""){
            $sql_update = "UPDATE `posts` SET `Title`='".$_POST["Title"]."',`Body`='".$_POST["Body"]."',`Slug`='".$_POST["Slug"]."' WHERE `idPost`=$idPost";
            $query = mysqli_query($conn,$sql_update);
            if($query){
                header("Location:?page=home");
            }
        }
    }


?>
<div class="box_edit">
    <form action="" method="post">
        <h2>Update Post</h2>
        <div class="form-item">
            <label>Title</label>
            <input type="text" name="Title" placeholder="Title" value="<?php echo $post["Title"];?>"/>
        </div>
        <div class="form-item">
            <label>Slug</label>
            <input type="text" name="Slug" placeholder="Slug" value="<?php echo $post["Slug"];?>"/>
        </div>
        <div class="form-item">
            <label>Body</label>
            <textarea cols="20" rows="5" name="Body" placeholder="Body"><?php echo strip_tags($post["Body"]);?></textarea>
        </div>
       
        <div class="form-item">
            <input type="submit" name="submit" value="Submit" />
        </div>
    </form>
</div>
<style>
    .box_edit{
        width:600px;
        margin:auto;
    }
    h2{
        font-size:23px;
        padding:5px;
        border-bottom:2px solid rgba(0,145,234,1);
        position:relative;
        z-index:1000;
        text-indent:10px;
        overflow: hidden;
        color:#fff;
        margin-bottom:10px;
    }
    h2::before{
        content: "";
        width: 200px;
        height: 100%;
        background: rgba(0,145,234,1);
        position: absolute;
        top: 0;
        left: -37px;
        z-index: -1;
        transform: skewX(30deg);
       
    }
   .form-item{
       margin-bottom:10px;
   }
    label{
        font-size:20px;
        display:block;
        font-weight:bold;
    }
    input,textarea{
        width:100%;
        padding:10px;
        box-sizing:border-box;
        border:none;
        box-shadow:0 0 1px  #000;
        outline:none;

    }
    input[type="submit"]{
        background: #000;
        color:#fff;
        font-weight:bold;
    }

</style>

Cũng giống như file add.php là cài đặt Form Html cho người dùng thao tác, nhưng chúng ta cần phải kiểm tra dữ liệu edit có tồn tại hay không, ví dụ: ?page=edit&id=2 , thì chúng ta cần $_GET["id"] xem id post này có trong cơ sở dữ liệu không

$idPost = $_GET["id"];
    $sql_edit = "SELECT * FROM `posts` WHERE `posts`.`idPost`=".$idPost;
    $result = mysqli_query($conn,$sql_edit);
    if(mysqli_num_rows($result)>0){
        $post = mysqli_fetch_assoc($result);  
    }else{

        echo "<script>alert('idPost không tồn tại');</script>";

        echo "<script>window.location.href='?page=home';</script>";
    }

Okay, nếu file này tồn tại và người dùng submit form thì ta thực hiện thao tác cập nhật dữ liệu với đoạn code dưới đây


    /* SET SUBMIT EDIT */
    if(isset($_POST["submit"])){
        if($_POST['Title'] !="" && $_POST["Body"]!="" && $_POST["Slug"]!=""){
            $sql_update = "UPDATE `posts` SET `Title`='".$_POST["Title"]."',`Body`='".$_POST["Body"]."',`Slug`='".$_POST["Slug"]."' WHERE `idPost`=$idPost";
            $query = mysqli_query($conn,$sql_update);
            if($query){
                header("Location:?page=home");
            }
        }
    }

+ File delete.php : ví dụ: ?page=delete&id=2

<?php
    if(isset($_GET["id"]) && $_GET["id"]){
        $idPost = $_GET["id"];
        $sql_check = "SELECT * FROM `posts` WHERE `idPost`=".$idPost;
        $check = mysqli_query($conn,$sql_check);
        if(mysqli_num_rows($check)>0){
            $sql_delete = "DELETE FROM `posts` WHERE `idPost`=".$idPost;
            $result = mysqli_query($conn,$sql_delete);
            if($result){
                header("Location:?page=home");
            }
            
        }
        header("Location:?page=home");
    }
    header("Location:?page=home");

?>

Đoạn code trên chúng ta kiểm tra id post có tồn tại trong database không, nếu có thì xóa nó luôn nhé kaka

x

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)