JSON CRUD Operation in PHP Tutorial

Introduction

In this tutorial, you will learn an effective way of Creating a CRUD Operation of JSON File Data in PHP language. This tutorial aims to provide a reference or guide for students or for those who are new to PHP Language to enhance their knowledge and programming capabilities of handling JSON File Data using the said programming language. Here, I have provided a snippets and sample web application's source code that is free to download.

What is CRUD?

In programming, CRUD stands for Create, Read, Update, and Delete functions. These are four basic functions common to web applications especially the applications that store and manage dynamic data.

  • Create - this function is being called for inserting or creating new data.
  • Read - this function is being called to fetch the dynamic data to display.
  • Update - this function is being called when updating the existing dynamic data.
  • Delete - this function is being called for deleting data.

How to Create CRUD for JSON File?

To Create CRUD functionalities or operations for your JSON file we can use the built-in functions of PHP called file_put_contents() and file_get_contents(). With these 2 functions, we can simply manipulate or update the JSON File Data in PHP.

Example

Let us assume that we have a JSON File named data.json. This JSON file contains the following structure.

  1. {
  2. "id" : #,
  3. "name" : "",
  4. "contact" : "",
  5. "address" : ""
  6. }

The JSON file will be filled with object items with the above structure and let's call it the list of members. Here's an example filled JSON file:

  1. [
  2. {
  3. "id": 1,
  4. "name": "John Smith",
  5. "contact": "0912354789",
  6. "address": "Sample Address"
  7. },
  8. {
  9. "id": 2,
  10. "name": "Claire Blake",
  11. "contact": "09789456123",
  12. "address": "Sample Address 102"
  13. }
  14. ]

PHP CRUD Functions

Then, to manipulate or manage the JSON File Data. You can use the following snippet. The CRUD Functions below are written using an Object-Orient Programming or OOP Approach in PHP.

  1. <?php
  2.  
  3. class Master {
  4. /**
  5.   * Get All JSON Data
  6.   */
  7. function get_all_data(){
  8. $json = (array) json_decode(file_get_contents('data.json'));
  9. $data = [];
  10. foreach($json as $row){
  11. $data[$row->id] = $row;
  12. }
  13. return $data;
  14. }
  15.  
  16. /**
  17.   * Get single JSON Data
  18.   */
  19. function get_data($id = ''){
  20. if(!empty($id)){
  21. $data = $this->get_all_data();
  22. if(isset($data[$id])){
  23. return $data[$id];
  24. }
  25. }
  26. return (object) [];
  27.  
  28. }
  29.  
  30. /**
  31.   * Insert Data into JSON File
  32.   */
  33. function insert_to_json(){
  34. $name = addslashes($_POST['name']);
  35. $contact = addslashes($_POST['contact']);
  36. $address = addslashes($_POST['address']);
  37.  
  38. $data = $this->get_all_data();
  39. $id = array_key_last($data) + 1;
  40. $data[$id] = (object) [
  41. "id" => $id,
  42. "name" => $name,
  43. "contact" => $contact,
  44. "address" => $address
  45. ];
  46. $json = json_encode(array_values($data), JSON_PRETTY_PRINT);
  47. $insert = file_put_contents('data.json', $json);
  48. if($insert){
  49. $resp['status'] = 'success';
  50. }else{
  51. $resp['failed'] = 'failed';
  52. }
  53. return $resp;
  54. }
  55. /**
  56.   * Update JSON File Data
  57.   */
  58. function update_json_data(){
  59. $id = $_POST['id'];
  60. $name = addslashes($_POST['name']);
  61. $contact = addslashes($_POST['contact']);
  62. $address = addslashes($_POST['address']);
  63.  
  64. $data = $this->get_all_data();
  65. $data[$id] = (object) [
  66. "id" => $id,
  67. "name" => $name,
  68. "contact" => $contact,
  69. "address" => $address
  70. ];
  71. $json = json_encode(array_values($data), JSON_PRETTY_PRINT);
  72. $update = file_put_contents('data.json', $json);
  73. if($update){
  74. $resp['status'] = 'success';
  75. }else{
  76. $resp['failed'] = 'failed';
  77. }
  78. return $resp;
  79. }
  80.  
  81. /**
  82.   * Delete Data From JSON File
  83.   */
  84.  
  85. function delete_data($id = ''){
  86. if(empty($id)){
  87. $resp['status'] = 'failed';
  88. $resp['error'] = 'Given Member ID is empty.';
  89. }else{
  90. $data = $this->get_all_data();
  91. if(isset($data[$id])){
  92. unset($data[$id]);
  93. $json = json_encode(array_values($data), JSON_PRETTY_PRINT);
  94. $update = file_put_contents('data.json', $json);
  95. if($update){
  96. $resp['status'] = 'success';
  97. }else{
  98. $resp['failed'] = 'failed';
  99. }
  100. }else{
  101. $resp['status'] = 'failed';
  102. $resp['error'] = 'Given Member ID is not existing on the JSON File.';
  103. }
  104. }
  105. return $resp;
  106. }
  107. }

Let's assume that the PHP Script File above is named master.php.

Explanations

Here are the explanations of each function you can see in the Master Class above:

get_all_data() - this function can be used for retrieving the JSON Data and returning it as an array of objects of the details of each member. This function is an example of a Read Function.

get_data([(int) $id]) - this function can be used for retrieving a single data from the JSON file whereas the ID is equal to the given ID on the parameter. If data with the given ID exists on the file then this will return the object data of the member otherwise it will only return an object w/ no data. This function is also an example of a Read Function.

insert_to_json() - this function can be called to insert new member data on the JSON File. The function requires POST data of name, contact, and address. The function will automatically generate an incrementing ID of the data. This function represents the Create Function of CRUD.

update_json_data() - this function can be called to update an existing object data on the JSON File. Like the insert_to_json function, this function also requires POST Data of name, contact, and address but here, POST id data is also required which will be used to identify the object data to update. This function represents the Update Function or the CRUD.

delete_data([(int) $id]) - this function is called for deleting an object data on the JSON File. This function requires an ID as the first and only parameter of the function to identify the object data to remove from the file. This function represents the Delete Function of CRUD.

Interface

Now using the snippets above, we can now create web pages for displaying the list of members and create the add/edit form interfaces.

Main Page

On the main page, we will list all the members from the JSON File. Here, we will also add the buttons where the user can redirect to the add member form, edit member details form, and delete member action page. Please note that on this file you must include the Master Class that I have provided above.

index.php

  1. <?php
  2. session_start();
  3. require_once('master.php');
  4. $master = new Master();
  5. $json_data = $master->get_all_data();
  6. ?>
  7. <!DOCTYPE html>
  8. <html lang="en">
  9. <meta charset="UTF-8">
  10. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  11. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  12. <title>PHP - JSON CRUD</title>
  13.  
  14. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  15. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  16. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  17.  
  18. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  19. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  20.  
  21. html, body{
  22. min-height:100%;
  23. width:100%;
  24. }
  25. </style>
  26. </head>
  27. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  28. <div class="container">
  29. <a class="navbar-brand" href="./">PHP - JSON CRUD</a>
  30. <div>
  31. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  32. </div>
  33. </div>
  34. </nav>
  35. <div class="container px-5 my-3">
  36. <h2 class="text-center">Create, Read, Update, and Delete Operation for JSON Data in PHP</h2>
  37. <div class="row">
  38. <!-- Page Content Container -->
  39. <div class="col-lg-10 col-md-11 col-sm-12 mt-4 pt-4 mx-auto">
  40. <div class="container-fluid">
  41. <!-- Handling Messages Form Session -->
  42. <?php if(isset($_SESSION['msg_success']) || isset($_SESSION['msg_error'])): ?>
  43. <?php if(isset($_SESSION['msg_success'])): ?>
  44. <div class="alert alert-success rounded-0">
  45. <div class="d-flex justify-content-between align-items-center">
  46. <div class="col-auto flex-shrink-1 flex-grow-1"><?= $_SESSION['msg_success'] ?></div>
  47. <div class="col-auto">
  48. <a href="#" onclick="$(this).closest('.alert').remove()" class="text-decoration-none text-reset fw-bolder mx-3">
  49. <i class="fa-solid fa-times"></i>
  50. </a>
  51. </div>
  52. </div>
  53. </div>
  54. <?php unset($_SESSION['msg_success']); ?>
  55. <?php endif; ?>
  56. <?php if(isset($_SESSION['msg_error'])): ?>
  57. <div class="alert alert-danger rounded-0">
  58. <div class="d-flex justify-content-between align-items-center">
  59. <div class="col-auto flex-shrink-1 flex-grow-1"><?= $_SESSION['msg_error'] ?></div>
  60. <div class="col-auto">
  61. <a href="#" onclick="$(this).closest('.alert').remove()" class="text-decoration-none text-reset fw-bolder mx-3">
  62. <i class="fa-solid fa-times"></i>
  63. </a>
  64. </div>
  65. </div>
  66. </div>
  67. <?php unset($_SESSION['msg_error']); ?>
  68. <?php endif; ?>
  69. <?php endif; ?>
  70. <!--END of Handling Messages Form Session -->
  71. <div class="card rounded-0 shadow">
  72. <div class="card-header">
  73. <div class="d-flex justify-content-between">
  74. <div class="card-title col-auto flex-shrink-1 flex-grow-1">Member List</div>
  75. <div class="col-atuo">
  76. <a class="btn btn-primary btn-sm btn-flat" href="member_form.php"><i class="fa fa-plus-square"></i> Add Member</a>
  77. </div>
  78. </div>
  79. </div>
  80. <div class="card-body">
  81. <div class="container-fluid">
  82. <table class="table table-stripped table-bordered">
  83. <col width="5%">
  84. <col width="20%">
  85. <col width="20%">
  86. <col width="35%">
  87. <col width="20%">
  88. <tr>
  89. <th class="text-center">ID</th>
  90. <th class="text-center">Name</th>
  91. <th class="text-center">Contact#</th>
  92. <th class="text-center">Address</th>
  93. <th class="text-center">Action</th>
  94. </tr>
  95. </thead>
  96. <?php foreach($json_data as $data): ?>
  97. <tr>
  98. <td class="text-center"><?= $data->id ?></td>
  99. <td><?= $data->name ?></td>
  100. <td><?= $data->contact ?></td>
  101. <td><?= $data->address ?></td>
  102. <td class="text-center">
  103. <a href="member_form.php?id=<?= $data->id ?>" class="btn btn-sm btn-outline-info rounded-0">
  104. <i class="fa-solid fa-edit"></i>
  105. </a>
  106. <a href="delete_data.php?id=<?= $data->id ?>" class="btn btn-sm btn-outline-danger rounded-0" onclick="if(confirm(`Are you sure to delete <?= $data->name ?> details?`) === false) event.preventDefault();">
  107. <i class="fa-solid fa-trash"></i>
  108. </a>
  109. </td>
  110. </tr>
  111. <?php endforeach; ?>
  112. </tbody>
  113. </table>
  114. </div>
  115. </div>
  116. </div>
  117. </div>
  118. </div>
  119. </div>
  120. </div>
  121. </body>
  122. </html>

Form Page

The following snippet is used for both Add and Edit Forms. If this page is loaded with an ID parameter on the URL and is existing on the JSON FILE, the page will serve as an Edit Form otherwise Add Form.

member_form.php

  1. <?php
  2. session_start();
  3. require_once('master.php');
  4. $master = new Master();
  5. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  6. if(isset($_POST['id']) && is_numeric($_POST['id']) && $_POST['id'] > 0){
  7. $save = $master->update_json_data();
  8. }else{
  9. $save = $master->insert_to_json();
  10. }
  11. if(isset($save['status'])){
  12. if($save['status'] == 'success'){
  13. if(isset($_POST['id']) && is_numeric($_POST['id']) && $_POST['id'] > 0)
  14. $_SESSION['msg_success'] = 'New Member has been added to JSON File Successfully';
  15. else
  16. $_SESSION['msg_success'] = 'Member Details has been updated to JSON File Successfully';
  17. header('location: ./');
  18. exit;
  19. }
  20. }else{
  21. $_SESSION['msg_error'] = 'Details has failed to save due to some error.';
  22. }
  23. }
  24. $data = $master->get_data(isset($_GET['id']) ? $_GET['id'] :'');
  25. ?>
  26. <!DOCTYPE html>
  27. <html lang="en">
  28. <meta charset="UTF-8">
  29. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  30. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  31. <title>Member Form | PHP - JSON CRUD</title>
  32.  
  33. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  34. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  35. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  36.  
  37. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  38. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  39.  
  40. html, body{
  41. min-height:100%;
  42. width:100%;
  43. }
  44. </style>
  45. </head>
  46. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  47. <div class="container">
  48. <a class="navbar-brand" href="./">PHP - JSON CRUD</a>
  49. <div>
  50. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  51. </div>
  52. </div>
  53. </nav>
  54. <div class="container px-5 my-3">
  55. <h2 class="text-center">Member Form</h2>
  56. <div class="row">
  57. <!-- Page Content Container -->
  58. <div class="col-lg-10 col-md-11 col-sm-12 mt-4 pt-4 mx-auto">
  59. <div class="container-fluid">
  60. <!-- Handling Messages Form Session -->
  61. <?php if(isset($_SESSION['msg_success']) || isset($_SESSION['msg_error'])): ?>
  62. <?php if(isset($_SESSION['msg_success'])): ?>
  63. <div class="alert alert-success rounded-0">
  64. <div class="d-flex justify-content-between align-items-center">
  65. <div class="col-auto flex-shrink-1 flex-grow-1"><?= $_SESSION['msg_success'] ?></div>
  66. <div class="col-auto">
  67. <a href="#" onclick="$(this).closest('.alert').remove()" class="text-decoration-none text-reset fw-bolder mx-3">
  68. <i class="fa-solid fa-times"></i>
  69. </a>
  70. </div>
  71. </div>
  72. </div>
  73. <?php unset($_SESSION['msg_success']); ?>
  74. <?php endif; ?>
  75. <?php if(isset($_SESSION['msg_error'])): ?>
  76. <div class="alert alert-danger rounded-0">
  77. <div class="d-flex justify-content-between align-items-center">
  78. <div class="col-auto flex-shrink-1 flex-grow-1"><?= $_SESSION['msg_error'] ?></div>
  79. <div class="col-auto">
  80. <a href="#" onclick="$(this).closest('.alert').remove()" class="text-decoration-none text-reset fw-bolder mx-3">
  81. <i class="fa-solid fa-times"></i>
  82. </a>
  83. </div>
  84. </div>
  85. </div>
  86. <?php unset($_SESSION['msg_error']); ?>
  87. <?php endif; ?>
  88. <?php endif; ?>
  89. <!--END of Handling Messages Form Session -->
  90.  
  91. <div class="card rounded-0 shadow">
  92. <div class="card-header">
  93. <div class="d-flex justify-content-between">
  94. <div class="card-title col-auto flex-shrink-1 flex-grow-1">Member List</div>
  95. <div class="col-atuo">
  96. <button class="btn btn-primary btn-sm btn-flat" id="add"><i class="fa fa-plus-square"></i> Add Member</button>
  97. </div>
  98. </div>
  99. </div>
  100. <div class="card-body">
  101. <div class="container-fluid">
  102. <?php if(isset($data->id)): ?>
  103. <p class="text-muted"><i>Update the details of <b><?= isset($data->name) ? $data->name : '' ?></b></i></p>
  104. <?php else: ?>
  105. <p class="text-muted"><i>Add New Member</b></i></p>
  106. <?php endif; ?>
  107. <form id="member-form" action="" method="POST">
  108. <input type="hidden" name="id" value="<?= isset($data->id) ? $data->id : '' ?>">
  109. <div class="mb-3">
  110. <label for="name" class="form-label">Member's Name</label>
  111. <input type="text" class="form-control rounded-0" id="name" name="name" required="required" value="<?= isset($data->name) ? $data->name : '' ?>">
  112. </div>
  113. <div class="mb-3">
  114. <label for="contact" class="form-label">Contact #</label>
  115. <input type="text" class="form-control rounded-0" id="contact" name="contact" required="required" value="<?= isset($data->contact) ? $data->contact : '' ?>">
  116. </div>
  117. <div class="mb-3">
  118. <label for="address" class="form-label">Address</label>
  119. <textarea rows="3" class="form-control rounded-0" id="address" name="address" required="required"><?= isset($data->address) ? $data->address : '' ?></textarea>
  120. </div>
  121. </form>
  122. </div>
  123. </div>
  124. <div class="card-footer text-center">
  125. <button class="btn btn-primary rounded-0" form="member-form"><i class="fa-solid fa-save"></i> Save Member</button>
  126. <a class="btn btn-light border rounded-0" href="./"><i class="fa-solid fa-times"></i> Cancel</a>
  127. </div>
  128. </div>
  129. </div>
  130. </div>
  131. <!-- End of Page Content Container -->
  132. </div>
  133. </div>
  134. </body>
  135. </html>

That's it! Now you can test the simple application on your end and see if it works well and achieve our goal for this tutorial. You can also download that source code zip file on this page by clicking the Download button below this article.

Snapshots

Main Page

PHP JSON CRUD - Main Page

Form Page

PHP JSON CRUD - Form Page

There you go. That's the end of this tutorial. I hope this JSON File CRUD operation using PHP Tutorial will help you with what you are looking for and that you'll find this useful for your current or future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment