--> Skip to main content

PHP CRUD Application Using Data From JSON File

The need to create CRUD applications (Create, Read, Update, Delete) often we do in developing a web. In this tutorial we will create PHP CRUD by using data from JSON File. Create means inserting data into database using INSERT SQL statement. Read means reading data from database using SELECT SQL statement. Update means updating records using UPDATE SQL query. Finally, Delete means deleting data from database using DELETE SQL statements.

In generally, we create CRUD operations in PHP by using relational database like MySQL. While in this tutorial all data is stored in JSON file extension instead of a database MySQL.

The output of CRUD Operations by using JSON file that we will discuss in this tutorial, shown in Figure 1 below:
(Figure.1)

Step by Step Guide: PHP CRUD Operations Using JSON File

1. Create JSON File
We create people.json file which contains : first name, last name, age and gender like the folllowing code :
{"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 index_crudjson.php file
This file will call data from people.json, so the data is displayed in this file:
<?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 insert.php file
This fie to get capture user input and then store data in people.json file :
<?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>

In inserting new data, all input must be filled. If there is input that is not filled, then will come out a alert dialog. The output of this insert.php file is shown in Figure.2 below:
(Figure.2)

4. Create update.php file
This file to perform the edit of certain data from 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. Create delete.php 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");
}


Comment Policy: Silahkan tuliskan komentar Anda yang sesuai dengan topik postingan halaman ini. Komentar yang berisi tautan tidak akan ditampilkan sebelum disetujui.
Buka Komentar
Tutup Komentar