In this article, we will discuss creating a CRUD Operation using JSON File in PHP. The PHP CRUD (Create, Read, Update, Delete) applications are often we do in building a website. JSON (JavaScript Object Notation) is lightweight and stores data as (key, value) pairs. JSON is the string notation that handles easy to read and write data. In our post, through implement the following functionality to build an example of how to connect PHP to a JSON File, create a new member record, fetch a member record from the JSON file, update the member record and delete the member record in the JSON file.
Array to JSON PHP in this example.
[
{
"name": "Anne Joyce",
"email": "[email protected]",
"phone": "987-654-3210",
"country": "USA",
"id": 7348621476
}
]
Displaying a Data
Create a new PHP file index.php and paste the codes below.
index.php<?php session_start(); // Retrieve session data $sessionData = !empty($_SESSION['sessionData'])?$_SESSION['sessionData']:''; // Include and initialize JSON class require_once 'Json.class.php'; $db = new Json(); // Fetch the member's data $members = $db->getRows(); // Get status message from session if(!empty($sessionData['status']['msg'])){ $statusMsg = $sessionData['status']['msg']; $statusMsgType = $sessionData['status']['type']; unset($_SESSION['sessionData']['status']); } ?> <!DOCTYPE html> <html lang="en"> <head> <title>PHP CRUD with JSON by CodeAT21</title> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <link rel="stylesheet" href="css/style.css"/> </head> <body> <div class="container"> <h1>PHP CRUD with JSON</h1> <!-- Display status message --> <?php if(!empty($statusMsg) && ($statusMsgType == 'success')){ ?> <div class="col-xs-12"> <div class="alert alert-success"><?php echo $statusMsg; ?></div> </div> <?php }elseif(!empty($statusMsg) && ($statusMsgType == 'error')){ ?> <div class="col-xs-12"> <div class="alert alert-danger"><?php echo $statusMsg; ?></div> </div> <?php } ?> <div class="row"> <div class="col-md-12 head"> <h5>Members</h5> <!-- Add link --> <div class="float-right"> <a href="addEdit.php" class="btn btn-success"> New Member</a> </div> </div> <!-- List the users --> <table class="table table-striped table-bordered"> <thead class="thead-dark"> <tr> <th>#</th> <th>Name</th> <th>Email</th> <th>Phone</th> <th>Country</th> <th>Action</th> </tr> </thead> <tbody id="userData"> <?php if(!empty($members)){ $count = 0; foreach($members as $row){ $count++; ?> <tr> <td><?php echo $count; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['email']; ?></td> <td><?php echo $row['phone']; ?></td> <td><?php echo $row['country']; ?></td> <td> <a href="addEdit.php?id=<?php echo $row['id']; ?>" class="btn btn-warning">edit</a> <a href="userAction.php?action_type=delete&id=<?php echo $row['id']; ?>" class="btn btn-danger" onclick="return confirm('Are you sure to delete?');">delete</a> </td> </tr> <?php } }else{ ?> <tr><td colspan="6">No member(s) found...</td></tr> <?php } ?> </tbody> </table> </div> </div> </body> </html>
- Insert – The Add link redirects to the addEdit.php page.
- Update – The Edit link redirects to the addEdit.php page.
- Delete – The Delete link redirects to the userAction.php page.
Create & Edit Records Form
Create a new PHP file addEdit.php and paste the codes below.
addEdit.php<?php session_start(); // Retrieve session data $sessionData = !empty($_SESSION['sessionData'])?$_SESSION['sessionData']:''; // Get member data $memberData = $userData = array(); if(!empty($_GET['id'])){ // Include and initialize JSON class include 'Json.class.php'; $db = new Json(); // Fetch the member data $memberData = $db->getSingle($_GET['id']); } $userData = !empty($sessionData['userData'])?$sessionData['userData']:$memberData; unset($_SESSION['sessionData']['userData']); $actionLabel = !empty($_GET['id'])?'Edit':'Add'; // Get status message from session if(!empty($sessionData['status']['msg'])){ $statusMsg = $sessionData['status']['msg']; $statusMsgType = $sessionData['status']['type']; unset($_SESSION['sessionData']['status']); } ?> <!DOCTYPE html> <html lang="en"> <head> <title>PHP CRUD with JSON by CodeAT21</title> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <link rel="stylesheet" href="css/style.css"/> </head> <body> <div class="container"> <h1>PHP CRUD with JSON</h1> <!-- Display status message --> <?php if(!empty($statusMsg) && ($statusMsgType == 'success')){ ?> <div class="col-xs-12"> <div class="alert alert-success"><?php echo $statusMsg; ?></div> </div> <?php }elseif(!empty($statusMsg) && ($statusMsgType == 'error')){ ?> <div class="col-xs-12"> <div class="alert alert-danger"><?php echo $statusMsg; ?></div> </div> <?php } ?> <div class="row"> <div class="col-md-12"> <h2><?php echo $actionLabel; ?> Member</h2> </div> <div class="col-md-6"> <form method="post" action="userAction.php"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" name="name" placeholder="Enter your name" value="<?php echo !empty($userData['name'])?$userData['name']:''; ?>" required=""> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" name="email" placeholder="Enter your email" value="<?php echo !empty($userData['email'])?$userData['email']:''; ?>" required=""> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" name="phone" placeholder="Enter contact no" value="<?php echo !empty($userData['phone'])?$userData['phone']:''; ?>" required=""> </div> <div class="form-group"> <label>Country</label> <input type="text" class="form-control" name="country" placeholder="Enter country name" value="<?php echo !empty($userData['country'])?$userData['country']:''; ?>" required=""> </div> <a href="index.php" class="btn btn-secondary">Back</a> <input type="hidden" name="id" value="<?php echo !empty($memberData['id'])?$memberData['id']:''; ?>"> <input type="submit" name="userSubmit" class="btn btn-success" value="Submit"> </form> </div> </div> </div> </body> </html>
- form Submit – data is posted to the userAction.php page.
PHP CRUD Operations with JSON (userAction.php)
Create a new PHP file userAction.php and paste the codes below.
userAction.php<?php session_start(); // Include and initialize DB class require_once 'Json.class.php'; $db = new Json(); // Set default redirect url $redirectURL = 'index.php'; if(isset($_POST['userSubmit'])){ // Get form fields value $id = $_POST['id']; $name = trim(strip_tags($_POST['name'])); $email = trim(strip_tags($_POST['email'])); $phone = trim(strip_tags($_POST['phone'])); $country = trim(strip_tags($_POST['country'])); $id_str = ''; if(!empty($id)){ $id_str = '?id='.$id; } // Fields validation $errorMsg = ''; if(empty($name)){ $errorMsg .= '<p>Please enter your name.</p>'; } if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)){ $errorMsg .= '<p>Please enter a valid email.</p>'; } if(empty($phone)){ $errorMsg .= '<p>Please enter contact no.</p>'; } if(empty($country)){ $errorMsg .= '<p>Please enter country name.</p>'; } // Submitted form data $userData = array( 'name' => $name, 'email' => $email, 'phone' => $phone, 'country' => $country ); // Store the submitted field value in the session $sessData['userData'] = $userData; // Submit the form data if(empty($errorMsg)){ if(!empty($_POST['id'])){ // Update user data $update = $db->update($userData, $_POST['id']); if($update){ $sessData['status']['type'] = 'success'; $sessData['status']['msg'] = 'Member data has been updated successfully.'; // Remove submitted fields value from session unset($sessData['userData']); }else{ $sessData['status']['type'] = 'error'; $sessData['status']['msg'] = 'Some problem occurred, please try again.'; // Set redirect url $redirectURL = 'addEdit.php'.$id_str; } }else{ // Insert user data $insert = $db->insert($userData); if($insert){ $sessData['status']['type'] = 'success'; $sessData['status']['msg'] = 'Member data has been added successfully.'; // Remove submitted fields value from session unset($sessData['userData']); }else{ $sessData['status']['type'] = 'error'; $sessData['status']['msg'] = 'Some problem occurred, please try again.'; // Set redirect url $redirectURL = 'addEdit.php'.$id_str; } } }else{ $sessData['status']['type'] = 'error'; $sessData['status']['msg'] = '<p>Please fill all the mandatory fields.</p>'.$errorMsg; // Set redirect url $redirectURL = 'addEdit.php'.$id_str; } // Store status into the session $_SESSION['sessData'] = $sessData; }elseif(($_REQUEST['action_type'] == 'delete') && !empty($_GET['id'])){ // Delete data $delete = $db->delete($_GET['id']); if($delete){ $sessData['status']['type'] = 'success'; $sessData['status']['msg'] = 'Member data has been deleted successfully.'; }else{ $sessData['status']['type'] = 'error'; $sessData['status']['msg'] = 'Some problem occurred, please try again.'; } // Store status into the session $_SESSION['sessData'] = $sessData; } // Redirect to the respective page header("Location:".$redirectURL); exit(); ?>
JSON Handler Class
Create a new PHP file Json.class.php and paste the codes below.
Json.class.php<?php /* This class is used for json file related (connect, insert, update, and delete) operations */ class Json{ private $jsonFile = "json_files/data.json"; public function getRows(){ if(file_exists($this->jsonFile)){ $jsonData = file_get_contents($this->jsonFile); $data = json_decode($jsonData, true); if(!empty($data)){ usort($data, function($a, $b) { return $b['id'] - $a['id']; }); } return !empty($data)?$data:false; } return false; } public function getSingle($id){ $jsonData = file_get_contents($this->jsonFile); $data = json_decode($jsonData, true); $singleData = array_filter($data, function ($var) use ($id) { return (!empty($var['id']) && $var['id'] == $id); }); $singleData = array_values($singleData)[0]; return !empty($singleData)?$singleData:false; } public function insert($newData){ if(!empty($newData)){ $id = time(); $newData['id'] = $id; $jsonData = file_get_contents($this->jsonFile); $data = json_decode($jsonData, true); $data = !empty($data)?array_filter($data):$data; if(!empty($data)){ array_push($data, $newData); }else{ $data[] = $newData; } $insert = file_put_contents($this->jsonFile, json_encode($data)); return $insert?$id:false; }else{ return false; } } public function update($upData, $id){ if(!empty($upData) && is_array($upData) && !empty($id)){ $jsonData = file_get_contents($this->jsonFile); $data = json_decode($jsonData, true); foreach ($data as $key => $value) { if ($value['id'] == $id) { if(isset($upData['name'])){ $data[$key]['name'] = $upData['name']; } if(isset($upData['email'])){ $data[$key]['email'] = $upData['email']; } if(isset($upData['phone'])){ $data[$key]['phone'] = $upData['phone']; } if(isset($upData['country'])){ $data[$key]['country'] = $upData['country']; } } } $update = file_put_contents($this->jsonFile, json_encode($data)); return $update?true:false; }else{ return false; } } public function delete($id){ $jsonData = file_get_contents($this->jsonFile); $data = json_decode($jsonData, true); $newData = array_filter($data, function ($var) use ($id) { return ($var['id'] != $id); }); $delete = file_put_contents($this->jsonFile, json_encode($newData)); return $delete?true:false; } } ?>
Related keywords
- PHP CRUD Operations with JSON File
- PHP CRUD Application Using Data From JSON File
- CRUD Operation On JSON File Using PHP
- Minimalist JSON CRUD written in PHP
- Create PHP 8 CRUD REST API with MySQL
- CRUD operations using JSON in JavaScript
- How to Create a Simple CRUD Application using only
- Build a CRUD App With Only JSON Files Using a Node.js API
- How to make CRUD operations in JSON
- How to do CRUD Operation using Json Server
- CRUD Operations Using AJAX/JSON
- CRUD in HTML, JavaScript, and jQuery Using the Web API
- Add, Update, Delete and Read JSON Data/File in PHP
- REST API CRUD using PHP
- REST API CRUD Example in PHP and MongoDB
- PHP insert json file
- Update json file
- Delete json file
- How to insert query using PHP JSON File