CRUD operations in the web application are used to manage data dynamically. Generally, the data is stored and manipulated in the database. There is also an alternative way to perform CRUD operations without a database. If you have any limitations with the database, JSON format is the best option to build a CRUD application with a JSON file instead of a database.
PHP CRUD operations with MySQL database is the best way to create (insert), read (select), update, and delete records in the web application. The JSON file can be used to integrate CRUD functionality in PHP instead of a database like MySQL. In this tutorial, we will show you how to create a simple CRUD application to list, view, add, edit, and delete records with JSON file using PHP.
We will implement the following functionality to build an example PHP CRUD script with JSON.
Before getting started to create a CRUD application with JSON file and PHP, take a look at the file structure.
php_crud_with_json/ ├── index.php ├── addEdit.php ├── userAction.php ├── Json.class.php ├── json_files/ ├── bootstrap/ │ └── bootstrap.min.css ├── css/ │ └── style.css └── images/
Since the JSON file will be used to store data without using any database, a JSON file is required. In the “json_files/” directory, the JSON files will be created dynamically to store the member’s information.
name
)email
)phone
)country
)The stored data format in the JSON file will look like below.
[
{
"name": "John Doe",
"email": "john@codex.com",
"phone": "123-456-7890",
"country": "USA",
"id": 1646116158
}
]
The Json class is a custom PHP library that handles all the CRUD-related operations (fetch, insert, update, and delete) with JSON file. Specify the directory where the JSON file will be stored and the name of the JSON file ($jsonFile).
<?php
/*
* JSON Class
* This class is used for json file related (connect, insert, update, and delete) operations
* @author CodexWorld.com
* @url http://www.codexworld.com
* @license http://www.codexworld.com/license
*/
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;
}
}
The userAction.php
file performs the CRUD operations using PHP and JSON (Json handler class). The code is executed based on the requested action.
update()
method of the Json class. Otherwise, put data in the JSON file using the insert()
method of the Json class.<?php
// Start session
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();
?>
We will use the Bootstrap library to make the table, form, and buttons look better. You can omit it to use custom stylesheet for HTML table, form, buttons, and other UI elements.
Include the CSS file of the Bootstrap library.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
In the index.php
file, we will retrieve the records from the JSON file using Json class and list them in a tabular format with Add, Edit, and Delete options.
addEdit.php
page to perform the Create operation.addEdit.php
page to perform the Update operation.userAction.php
file with action_type=delete
and id
params. In the userAction.php
file, the record is deleted from the JSON file based on the unique identifier (id).<?php
// Start session
session_start();
// Retrieve session data
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
// 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($sessData['status']['msg'])){
$statusMsg = $sessData['status']['msg'];
$statusMsgType = $sessData['status']['type'];
unset($_SESSION['sessData']['status']);
}
?>
<!-- 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"><i class="plus"></i> 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>
<?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>
The addEdit.php
handles the create and update form functionality.
id
parameter exists on the URL, the existing member data will be retrieved from the database based on this ID and the form fields will be pre-filled.<?php
// Start session
session_start();
// Retrieve session data
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
// 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($sessData['userData'])?$sessData['userData']:$memberData;
unset($_SESSION['sessData']['userData']);
$actionLabel = !empty($_GET['id'])?'Edit':'Add';
// Get status message from session
if(!empty($sessData['status']['msg'])){
$statusMsg = $sessData['status']['msg'];
$statusMsgType = $sessData['status']['type'];
unset($_SESSION['sessData']['status']);
}
?>
<!-- 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>
PHP CRUD Operations with Search and Pagination
This JSON CRUD is a lightweight and easy-to-use script to integrate data management functionality without using the database. The data listing, view, insert, update, and delete operations can be handled with JSON files using PHP. You can enhance the functionality of this CRUD script to make it user-friendly by integrating PHP CRUD operations without page refresh using JSON file.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Good JOB, Thanks a lot.
Thanks
Thanks by this great contribuition! Will be very usefull to me and others developers!