Pusat Ilmu Secara Detil

Bootstrap PHP Crud dengan Data dari JSON File

Bootstrap PHP Crud dengan Data dari JSON File

Kebutuhan membuat aplikasi CRUD (Create, Read, Update, Delete) sering kita lakukan dalam mengdevelop sebuah web. Dalam tutorial ini kita akan membuat PHP CRUD dengan menggunakan data dari JSON File.

Umumnya kita membuat aplikasi PHP CRUD dengan menggunakan database relational seperti MySQL. Sedangkan dalam tutorial ini semua data disimpan dalam sebuah file berekstensi JSON. Jika anda membutuhkan contoh pembuatan PHP CRUD dengan database MySQL, silahkan kunjungi tutorial "Bootstrap CRUD dengan PHP Mysql".

Output dari CRUD dengan menggunakan JSON File yang akan kita bahas dalam tutorial kali ini, ditunjukkan oleh Gambar.1 dibawah ini :

(Gambar.1 )

Seperti yang terlihat pada Gambar.1 kita memiliki 4 buah fitur :
  • Create, diwakili dengan menu Insert Data yang bertujuan untuk menambah data baru.
  • Read secara otomatis membaca data dari file JSON.
  • Delete untuk menghapus data tertentu dari file JSON.
  • Update untuk mengubah atau edit data tertentu dari file JSON.

Langkah-langkahnya

1. Membuat data JSON File
Disini file json diberinama people.json yang berisikan item data seperti berikut :
{"records":
  [
      {"fname":"Lama","lname":"Harsa","age":"25","gender":"Female"},
      {"fname":"ahmad","lname":"hardi","age":"33","gender":"Male"},
   {"fname":"Fitria","lname":"Desiew","age":"28","gender":"Female"}
  ]
}

2. Create file index_crudjson.php
File ini akan mengload data-data dari people.json, sehingga data-datanya ditampilkan dalam file ini :
<?php
$getfile = file_get_contents('people.json');
$jsonfile = json_decode($getfile);
?>
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta name="author" content="ilmu-detil.blogspot.com">
 <title>Tutorial CRUD  JSON DATA</title>
 <link rel="stylesheet" href="assets/css/bootstrap.min.css">
 <link rel="stylesheet" href="assets/css/ilmudetil.css">
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top">
 <div class="container">
  <div class="navbar-header">
   <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    <span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
   </button>
   <a class="navbar-brand" href="index.html">
   Pusat Ilmu Secara Detil</a>
  </div>
  <div class="navbar-collapse collapse">
   <ul class="nav navbar-nav navbar-left">
    <li class="clr1 active"><a href="index.html">Home</a></li>
    <li class="clr2"><a href="">Bootstrap</a></li>
    <li class="clr3"><a href="">AngularJS</a></li>
   </ul>
  </div>
 </div>
</nav>
</br></br></br></br>
<div class="container">
 <div class="jumbotron">
  <h3>Tutorial Bootstrap PHP CRUD From JSON File</h3>      
  <p>Create, Read, Update and Delete Data from JSON</p>      
 </div>
</div>
<div class="container">
 <div class="btn-toolbar">
  <a class="btn btn-primary" href="insert.php"><i class="icon-plus"></i> Insert Data</a>
  <div class="btn-group"> </div>
 </div>
</div>
<br>
<br>
<div class="container">
 <div class ="row">
  <div class="col-md-9">
   <table class="table table-striped table-bordered table-hover">
    <tr>
     <th>No.</th>
     <th>First Name</th>
     <th>Last Name</th>
     <th>Age</th>
     <th>Gender</th>
     <th>Action</th>
    </tr>  
    <?php $no=0;foreach ($jsonfile->records as $index => $obj): $no++;  ?>
    <tr>
     <td><?php echo $no; ?></td>
     <td><?php echo $obj->fname; ?></td>
     <td><?php echo $obj->lname; ?></td>
     <td><?php echo $obj->age; ?></td>
     <td><?php echo $obj->gender; ?></td>
     <td>
      <a class="btn btn-xs btn-primary" href="update.php?id=<?php echo $index; ?>">Edit</a>
      <a class="btn btn-xs btn-danger" href="delete.php?id=<?php echo $index; ?>">Delete</a>
     </td>
    </tr>
    <?php endforeach; ?>
   </table>
  </div> 
 </div>
</div>
</body>
</html>

3. Create file insert.php
File ini akan membuat data baru lalu disimpan ke dalam JSON File, begitu proses selesai kemudian file utama (index_crudjson.php) akan menampilkan hasil penambahan data tersebut.
<?php 
    if ( !empty($_POST)) { 
    
        $fname  = $_POST['fname'];
        $lname  = $_POST['lname'];
        $age    = $_POST['age'];
        $gender = $_POST['gender'];
      
  $file = file_get_contents('people.json');
  $data = json_decode($file, true);
  unset($_POST["add"]);
  $data["records"] = array_values($data["records"]);
  array_push($data["records"], $_POST);
  file_put_contents("people.json", json_encode($data));
  header("Location: index_crudjson.php");
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta name="description" content="tutorial-boostrap-merubaha-warna">
 <meta name="author" content="ilmu-detil.blogspot.com">
 <title>Tutorial CRUD  JSON DATA</title>
 <link rel="stylesheet" href="assets/css/bootstrap.min.css">
 <style type="text/css">
 .navbar-default {
  background-color: #3b5998;
  font-size:18px;
  color:#ffffff;
 }
 </style>
</head>
<body>
<nav class="navbar navbar-default">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>                        
      </button>
      <h4>Pusat Ilmu Secara Detil</h4>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
    </div>
  </div>
</nav>
<!-- /.navbar -->
<div class="container">
        <div class="row">
  <div class="col-sm-5 col-sm-offset-3"><h3>Create a User</h3>
        <form method="POST" action="">
   <div class="form-group">
    <label for="inputFName">First Name</label>
    <input type="text" class="form-control" required="required" id="inputFName" name="fname" placeholder="First Name">
    <span class="help-block"></span>
   </div>
   
   <div class="form-group ">
    <label for="inputLName">Last Name</label>
    <input type="text" class="form-control" required="required" id="inputLName" name="lname" placeholder="Last Name">
          <span class="help-block"></span>
   </div>
   
   <div class="form-group">
    <label for="inputAge">Age</label>
    <input type="number" required="required" class="form-control" id="inputAge" name="age" placeholder="Age">
    <span class="help-block"></span>
   </div>
    <div class="form-group">
     <label for="inputGender">Gender</label>
     <select class="form-control" required="required" id="inputGender" name="gender" >
      <option>Please Select</option>
      <option value="Male">Male</option>
      <option value="Female">Female</option>
     </select>
     <span class="help-block"></span>
          </div>
    
   <div class="form-actions">
     <button type="submit" class="btn btn-success">Create</button>
     <a class="btn btn btn-default" href="index_crudjson.php">Back</a>
   </div>
  </form>
        </div></div>        
</div>
</body>
</html>

Dalam proses insert data baru, semua inputan harus diisi. Jika ada inputan yang tidak diisi, maka akan keluar sebuah peringatan . Output dari insert.php ini ditunjukkan oleh Gambar.2 dibawah ini :

(Gambar.2 )


4. Create file update.php
File ini untuk melakukan proses edit dari data tertentu dari JSON File :
<?php
if (isset($_GET["id"])) {
    $id = (int) $_GET["id"];
    $getfile = file_get_contents('people.json');
    $jsonfile = json_decode($getfile, true);
    $jsonfile = $jsonfile["records"];
    $jsonfile = $jsonfile[$id];
}

if (isset($_POST["id"])) {
    $id = (int) $_POST["id"];
    $getfile = file_get_contents('people.json');
    $all = json_decode($getfile, true);
    $jsonfile = $all["records"];
    $jsonfile = $jsonfile[$id];

    $post["fname"] = isset($_POST["fname"]) ? $_POST["fname"] : "";
    $post["lname"] = isset($_POST["lname"]) ? $_POST["lname"] : "";
    $post["age"] = isset($_POST["age"]) ? $_POST["age"] : "";
    $post["gender"] = isset($_POST["gender"]) ? $_POST["gender"] : "";

    if ($jsonfile) {
        unset($all["records"][$id]);
        $all["records"][$id] = $post;
        $all["records"] = array_values($all["records"]);
        file_put_contents("people.json", json_encode($all));
    }
    header("Location:index_crudjson.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta name="description" content="tutorial-boostrap-merubaha-warna">
 <meta name="author" content="ilmu-detil.blogspot.com">
 <title>Tutorial Boostrap </title>
 <link rel="stylesheet" href="assets/css/bootstrap.min.css">
 
 <style type="text/css">
 .navbar-default {
  background-color: #3b5998;
  font-size:18px;
  color:#ffffff;
 }
 </style>
</head>
<body>
<nav class="navbar navbar-default">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>                        
      </button>
      <h4>Detailed Technology Center</h4>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
      
    </div>
  </div>
</nav>
<!-- /.navbar -->

<div class="container">
    <div class="row">
        <div class="row">
            <h3>Update a User</h3>
        </div>
            
        <?php if (isset($_GET["id"])): ?>
  <form method="POST" action="update.php">
  <div class="col-md-6">
   <input type="hidden" value="<?php echo $id ?>" name="id"/>
   <div class="form-group">
    <label for="inputFName">First Name</label>
    <input type="text" class="form-control" required="required" id="inputFName" value="<?php echo $jsonfile["fname"] ?>" name="fname" placeholder="First Name">
    <span class="help-block"></span>
   </div>
   
   <div class="form-group">
    <label for="inputLName">Last Name</label>
    <input type="text" class="form-control" required="required" id="inputLName" value="<?php echo $jsonfile["lname"] ?>" name="lname" placeholder="Last Name">
    <span class="help-block"></span>
   </div>
   
   <div class="form-group">
    <label for="inputAge">Age</label>
    <input type="number" required="required" class="form-control" id="inputAge" value="<?php echo $jsonfile["age"] ?>" 
     name="age" placeholder="Age">
    <span class="help-block"></span>
   </div>
   
   <div class="form-group">
    <label for="inputGender">Gender</label>
    <select class="form-control" required="required" id="inputGender" name="gender" >
    <option>Please Select</option>
    <option value="Male" <?php echo  $jsonfile["gender"] == 'Male'?'selected':'';?>>Male</option>
    <option value="Female" <?php echo $jsonfile["gender"] == 'Female'?'selected':'';?>>Female</option>
    </select>
    <span class="help-block"></span>
   </div>
    
   <div class="form-actions">
    <button type="submit" class="btn btn-primary">Update</button>
    <a class="btn btn btn-default" href="index_crudjson.php">Back</a>
   </div>
  </div>
  </form>
  <?php endif; ?>     
    </div> 
</div> 
</body>
</html>

5. File delete.php
File ini akan menerima id yang dikirimkan oleh file index_crudjson.php untuk memproses penghapusan data  dari JSON file.
<?php

if (isset($_GET["id"])) {
    $id = (int) $_GET["id"];
    $all = file_get_contents('people.json');
    $all = json_decode($all, true);
    $jsonfile = $all["records"];
    $jsonfile = $jsonfile[$id];

    if ($jsonfile) {
        unset($all["records"][$id]);
        $all["records"] = array_values($all["records"]);
        file_put_contents("people.json", json_encode($all));
    }
    header("Location: index_crudjson.php");
}


Share this:

Related Posts
Disqus Comments