Cara Membuat CRUD dengan PHP dan MySQL

 ⊛ • 24 mins read

Main Image

Intro

Halo semuanya, apa kabar? Mudah-mudahan selalu diberikan kesehatan ya. Pada kali ini saya akan membagikan tutorial mengenai Cara Membuat CRUD dengan PHP dan MySQL. Pasti kalian bertanya-tanya nih, apa itu CRUD?

CRUD merupakan singkatan dari Create Read Update Delete. Nah, di sini saya akan mencoba mempraktikkan CRUD untuk membuat data mahasiswa (Create), menampilkan data mahasiswa (Read), mengedit data mahasiswa (Update), dan menghapus data mahasiswa (Delete).

Persiapan

Dalam tutorial ini, saya menggunakan resources sebagai berikut:

Resources Versi
LAMPP (XAMPP untuk Windows) 8.0.0-2
PHP 8.0.0
Bootstrap (Untuk tampilan) 5.0.0-beta1

Membuat Database

  1. Buka XAMPP lalu start Apache dan MySQL, untuk linux jalankan
    1
    
     sudo /opt/lampp/lampp start
    
  2. Buka database phpMyAdmin di browser dengan mengakses database di localhost

  3. Masukkan nama database db_mahasiswa dan klik Create

  4. Buat tabel tbl_mahasiswa dengan kode seperti berikut
    1
    2
    3
    4
    5
    6
    
     CREATE TABLE `db_mahasiswa`.`tbl_mahasiswa` (
         `id` INT(11) NOT NULL AUTO_INCREMENT,
         `nama` VARCHAR(256) NOT NULL,
         `nim` VARCHAR(256) NOT NULL,
         PRIMARY KEY (`id`)
     ) ENGINE = InnoDB;
    

Pembuatan CRUD

  1. Dalam folder htdocs, buatlah folder dengan nama crud-app

  2. Masuk ke dalam folder crud-app dan buatlah file index.php, config.php, create.php, delete.php, dan update.php sehingga struktur folder seperti berikut:
    1
    2
    3
    4
    5
    6
    
     crud-app                Folder utama
     ├── config.php          Untuk pengaturan database
     ├── create.php          Untuk input data mahasiswa
     ├── delete.php          Untuk menghapus data mahasiswa
     ├── index.php           Halaman utama sekaligus untuk membaca data mahasiswa
     └── update.php          Untuk mengedit data mahasiswa dan mengupdatenya
    
  3. Selanjutnya buka file config.php dan masukkan kode untuk pengaturan database seperti berikut
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
     <?php
     $DB_USER = 'root';
     $DB_PASS = '';
    
     try {
         $db = new PDO('mysql:host=localhost;dbname=db_mahasiswa', $DB_USER, $DB_PASS);
     } catch (PDOException $e) {
         print "Error!: " . $e->getMessage();
         die();
     }
     ?>
    
  4. Setelah itu buka file index.php dan masukkan kode untuk membaca data mahasiswa
    1
    2
    3
    4
    5
    
     <?php
     include 'config.php';
     $stmt = $db->prepare('SELECT * FROM tbl_mahasiswa');
     $stmt->execute();
     ?>
    
  5. Masih di file index.php, tambahkan juga kode untuk preview dan tampilan data dibawah kode sebelumnya
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    
     <!DOCTYPE html>
     <html>
     <head>
         <meta charset='utf-8'>
         <meta http-equiv='X-UA-Compatible' content='IE=edge'>
         <title>Home</title>
         <meta name='viewport' content='width=device-width, initial-scale=1'>
            
         <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1' crossorigin='anonymous'>
         <script src='https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js' integrity='sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW' crossorigin='anonymous'></script>
         <script src="https://use.fontawesome.com/releases/v5.15.2/js/all.js" data-auto-replace-svg="nest"></script>
    
     </head>
     <body>
         <nav class='navbar navbar-expand-lg navbar-dark bg-dark'>
             <div class='container-fluid'>
                 <a class='navbar-brand' href='./'>
                     <i class='fas fa-book d-inline-block align-top' width='30' height='24'></i>
                     Data Mahasiswa
                 </a>
                 <button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#navbarSupportedContent' aria-controls='navbarSupportedContent' aria-expanded='false' aria-label='Toggle navigation'>
                 <span class='navbar-toggler-icon'></span>
                 </button>
                 <div class='collapse navbar-collapse' id='navbarSupportedContent'>
                 <ul class='navbar-nav me-auto mb-2 mb-lg-0'>
                     <li class='nav-item'>
                         <a class='nav-link active' aria-current='page' href='./'>Home</a>
                     </li>
                     <li class='nav-item'>
                         <a class='nav-link' aria-current='page' href='./create.php'>Tambah Item</a>
                     </li>
                 </ul>
                 </div>
             </div>
         </nav>
         <div class='container' style='margin-top: 3rem;'>
         <div class="card">
             <div class="card-header" style="display: flex; justify-content: space-between">
             Data Mahasiswa
             <?php
             if ($stmt->rowCount() > 0) {
             echo '<a href="./create.php" class="btn btn-primary btn-sm"><i class="far fa-plus-square"></i> Tambah Item</a>';
             }?>
             </div>
             <div class="card-body">
             <?php
             if ($stmt->rowCount() > 0) {
                 $data_mhs = $stmt->fetchAll(PDO::FETCH_ASSOC);?>
                 <table class='table table-striped table-hover table-bordered'>
                 <thead>
                     <tr class='table-dark' style='text-align: center;'>
                     <th scope='col'>ID</th>
                     <th scope='col'>NAMA</th>
                     <th scope='col'>NIM</th>
                     <th scope='col'>AKSI</th>
                     </tr>
                 </thead>
                 <tbody>
                     <?php
                     foreach ($data_mhs as $mhs) {
                         print "
                         <tr>
                         <th scope='row'>".$mhs['id']."</th>
                         <td>".$mhs['nama']."</td>
                         <td>".$mhs['nim']."</td>
                         <td>
                             <div style='display: flex; justify-content: space-evenly'>
                             <form action='./update.php' method='POST'>
                                 <input name='id' value='".$mhs['id']."' hidden>
                                 <input name='nama' value='".$mhs['nama']."' hidden>
                                 <input name='nim' value='".$mhs['nim']."' hidden>
                                 <button type='submit' class='btn btn-warning btn-sm'><i class='far fa-edit'></i></button>
                             </form>
                             <form action='./delete.php' method='POST'>
                                 <input name='id' value='".$mhs['id']."' hidden>
                                 <button type='submit' class='btn btn-danger btn-sm'><i class='far fa-trash-alt'></i></button>
                             </form>
                             </div>
                         </td>
                         </tr>";
                     }
                     ?>
                 </tbody>
                 </table>
             <?php } else { ?>
                 <h5 class="card-title">Database Kosong</h5>
                 <p class="card-text">Untuk menambah item pada database, klik tombol di bawah ini.</p>
                 <a href="./create.php" class="btn btn-primary"><i class="far fa-plus-square"></i> Tambah Item</a>
             <?php }?>
             </div>
         </div>
         </div>
     </body>
     </html>
    
  6. Selanjutnya buka file create.php dan masukkan kode untuk menambahkan data mahasiswa
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
     <?php
     include 'config.php';
    
     if (!empty($_POST)) {
         $nama = isset($_POST['nama']) ? $_POST['nama'] : ' ';
         $nim = isset($_POST['nim']) ? $_POST['nim'] : ' ';
         try {
             $stmt = $db->prepare("INSERT INTO `tbl_mahasiswa`(`id`, `nama`, `nim`) VALUES (null,:nama,:nim)");
             $stmt->bindParam(':nama', htmlspecialchars(strip_tags($nama)));
             $stmt->bindParam(':nim', htmlspecialchars(strip_tags($nim)));
             $stmt->execute();
             header('location: ./');
         } catch (PDOException $e) {
             echo $e->getMessage();
         }
     }
     ?>
    
  7. Untuk tampilannya, masukkan kode berikut setelah kode di atas
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    
     <!DOCTYPE html>
     <html>
     <head>
         <meta charset='utf-8'>
         <meta http-equiv='X-UA-Compatible' content='IE=edge'>
         <title>Create</title>
         <meta name='viewport' content='width=device-width, initial-scale=1'>
            
         <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1' crossorigin='anonymous'>
         <script src='https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js' integrity='sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW' crossorigin='anonymous'></script>
         <script src="https://use.fontawesome.com/releases/v5.15.2/js/all.js" data-auto-replace-svg="nest"></script>
            
     </head>
     <body>
         <nav class='navbar navbar-expand-lg navbar-dark bg-dark'>
             <div class='container-fluid'>
                 <a class='navbar-brand' href='./'>
                     <i class='fas fa-book d-inline-block align-top' width='30' height='24'></i>
                     Data Mahasiswa
                 </a>
                 <button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#navbarSupportedContent' aria-controls='navbarSupportedContent' aria-expanded='false' aria-label='Toggle navigation'>
                 <span class='navbar-toggler-icon'></span>
                 </button>
                 <div class='collapse navbar-collapse' id='navbarSupportedContent'>
                 <ul class='navbar-nav me-auto mb-2 mb-lg-0'>
                     <li class='nav-item'>
                         <a class='nav-link' aria-current='page' href='./'>Home</a>
                     </li>
                     <li class='nav-item'>
                         <a class='nav-link active' aria-current='page' href='./create.php'>Tambah Item</a>
                     </li>
                 </ul>
                 </div>
             </div>
         </nav>
         <div class='container' style='margin-top: 3rem;'>
             <div class="card">
                 <div class="card-header">
                 Tambah Item
                 </div>
                 <div class="card-body">
                     <form action="./create.php" method="POST">
                         <div class="mb-3">
                             <label for="nama" class="form-label">Nama</label>
                             <input type="text" class="form-control" id="nama" name="nama" placeholder="Nama" required><br>
                             <label for="nim" class="form-label">NIM</label>
                             <input type="text" class="form-control" id="nim" name="nim" placeholder="NIM" required><br>
                             <div style="display: flex; justify-content: space-between;">
                                 <a href="./" class="btn btn-danger">Batal</a>
                                 <input type="submit" class="btn btn-primary" value="Tambah">
                             </div>
                         </div>
                     </form>
                 </div>
             </div>
         </div>
     </body>
     </html>
    
  8. Setelah selesai, buka file update.php lalu masukkan kode untuk mengedit dan mengupdate data mahasiswa
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    
     <?php
     include 'config.php';
    
     if (!empty($_POST)) {
         if (isset($_POST['z'])) {
             try {
                 $id = isset($_POST['id']) ? $_POST['id'] : ' ';
                 $nama = isset($_POST['nama']) ? $_POST['nama'] : ' ';
                 $nim = isset($_POST['nim']) ? $_POST['nim'] : ' ';
                 $stmt = $db->prepare('UPDATE tbl_mahasiswa SET nama = :nama, nim = :nim WHERE id = :id ');
                 $stmt->bindParam(':nama', htmlspecialchars(strip_tags($nama)));
                 $stmt->bindParam(':nim', htmlspecialchars(strip_tags($nim)));
                 $stmt->bindParam(':id', htmlspecialchars(strip_tags($id)));
                 $stmt->execute();
                 print_r($_POST);
                 header('location: ./');
             } catch (PDOException $e) {
                 echo $e->getMessage();
             }
         } else {
             $id = isset($_POST['id']) ? $_POST['id'] : ' ';
             $nama = isset($_POST['nama']) ? $_POST['nama'] : ' ';
             $nim = isset($_POST['nim']) ? $_POST['nim'] : ' ';
             $data_mhs = $_POST;
         }   
     }
     ?>
    
  9. Untuk tampilannya, masukkan kode berikut
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    
     <!DOCTYPE html>
     <html>
     <head>
         <meta charset='utf-8'>
         <meta http-equiv='X-UA-Compatible' content='IE=edge'>
         <title>Update</title>
         <meta name='viewport' content='width=device-width, initial-scale=1'>
            
         <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1' crossorigin='anonymous'>
         <script src='https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js' integrity='sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW' crossorigin='anonymous'></script>
         <script src="https://use.fontawesome.com/releases/v5.15.2/js/all.js" data-auto-replace-svg="nest"></script>
            
     </head>
     <body>
         <nav class='navbar navbar-expand-lg navbar-dark bg-dark'>
             <div class='container-fluid'>
                 <a class='navbar-brand' href='./'>
                     <i class='fas fa-book d-inline-block align-top' width='30' height='24'></i>
                     Data Mahasiswa
                 </a>
                 <button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#navbarSupportedContent' aria-controls='navbarSupportedContent' aria-expanded='false' aria-label='Toggle navigation'>
                 <span class='navbar-toggler-icon'></span>
                 </button>
                 <div class='collapse navbar-collapse' id='navbarSupportedContent'>
                 <ul class='navbar-nav me-auto mb-2 mb-lg-0'>
                     <li class='nav-item'>
                         <a class='nav-link active' aria-current='page' href='./'>Home</a>
                     </li>
                     <li class='nav-item'>
                         <a class='nav-link' aria-current='page' href='./create.php'>Tambah Item</a>
                     </li>
                 </ul>
                 </div>
             </div>
         </nav>
         <div class='container' style='margin-top: 3rem;'>
             <div class="card">
                 <div class="card-header">
                 Edit Item
                 </div>
                 <div class="card-body">
                     <form action="./update.php" method="POST">
                         <div class="mb-3">
                             <label for="id" class="form-label">Id</label>
                             <input type="text" id="id" name="id" hidden value="<?php echo $data_mhs['id']; ?>">
                             <input type="text" class="form-control" id="id" name="id" placeholder="Id" required disabled value="<?php echo $data_mhs['id']; ?>"><br>
                             <label for="nama" class="form-label">Nama</label>
                             <input type="text" class="form-control" id="nama" name="nama" placeholder="Nama" required value="<?php echo $data_mhs['nama']; ?>"><br>
                             <label for="nim" class="form-label">NIM</label>
                             <input type="text" class="form-control" id="nim" name="nim" placeholder="NIM" required value="<?php echo $data_mhs['nim']; ?>"><br>
                             <input name="z" value="a" hidden>
                             <div style="display: flex; justify-content: space-between;">
                                 <button class="btn btn-danger" onclick="./"><i class="fas fa-times"></i> Batal</button>
                                 <button type="submit" class="btn btn-success"><i class="fas fa-check"></i> Simpan</button>
                             </div>
                         </div>
                     </form>
                 </div>
             </div>
         </div>
     </body>
     </html>
    
  10. Selanjutnya buka file delete.php dan masukkan kode untuk menghapus data mahasiswa
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    <?php
    include 'config.php';
    
    if (!empty($_POST)) {
        $id = isset($_POST['id']) ? $_POST['id'] : ' ';
        try {
            $stmt = $db->prepare('DELETE FROM tbl_mahasiswa WHERE id = :id');
            $stmt->bindParam(':id', htmlspecialchars(strip_tags($id)));
            $stmt->execute();
            header('location: ./');
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }
    ?>
    

Testing

Setelah semua langkah diatas dilakukan, sekarang saatnya kita mencobanya dengan membuka http://localhost/crud-app di browser kesayanganmu.

Berikut ini adalah video testing yang saya lakukan

Hasil Akhir

Laman Screenshot
Home
Tambah Item
Edit Item

License: CC-BY

Share this post:


Tags Other Articles Perbedaan Antara Div dan Span Tag