How to create update read and delete data in a json file with php

Updated: 20-Oct-2022 / Tags: PHP and JSON / Views: 1984 - Author: George

Introduction

Hello everyone, in this tutorial we are going to see how to create a CRUD back-end application using php.
CRUD stands for create, read, update, and delete. So we are going to insert, update, read, and delete users in a JSON file.

We are going to create a User Class that will execute all the above actions. So let's start.

Project's folder

Let's quick see what files we need.

  • We need a user.class.php file to write our User Class.
  • We need a script.php file which we are going to run in the browser to execute our commands.
  • And we need a users.json file to insert the users.
  • All the files are obviously in the same root folder.

Now that we have set our project's folder, lets start with the JSON file.

The users.json file

The only thing that we need in the json file is an empty array, in which we are going to insert the users. If we don't initialize the json file with an empty array the code will not work.

[]

Now let's move to the script.php file. This is the file which we will execute in the browser.

The script.php file

In the script.php file for starter we are going to require the user.class.php file, so we have access to the User Class.

<php
	require("user.class.php");

	$new_user = [
		"username" => "Bob",
		"password" => "7890",
		"status" => "active"
	];
  • In line 4 we have an array called $new_user which holds the username, the password, and the status of a user. Take notice that the user don't have an id field, like we have in an SQL table. We are going to add an id field, which will be incremented by one, in the User Class.
    We will use the $new_user array to perform our actions.

    We will come back to this file several times to execute the class methods that we are gonna write.
    Now let's move to the user.class.php file to write the properties and methods that we need.

The User Class

The first thing that we do in the user.class.php file, is to define the User Class.

<?php
class User{

Now inside the class we are going to define the class properties. We are going to set all properties to private. This means that our properties are accessible only from inside the class. There is no need to set them as public.
All properties will be initialized with their values in the class's constructor.

	// Class methods -----------
	private $json_file;
	private $stored_users;
	private $number_of_records;
	private $ids = [];
	private $usernames = [];

Let's "see" our properties one by one.

  • In the private $json_file property we are going to set the json file's filepath.
  • In the private $stored_users property we are going to store all users that we have already in the json file.
  • In the private $number_of_records property we are going to count and store how many users we have in the json file.
  • In the private $ids = [] array property we are going to store all the users id's that are already stored in the json file. We want the user's id's so we can add to every user an id which will be incremented by one. It will be like the auto_increment setting in a mysql database.
  • And last in the private $usernames = [] array property we are going to store all users usernames from the json file. We do this because we are going to check the private $usernames = [] property if the given username already exists. The application will not accept usernames that already exists.

    That's all the properties we need, now let's write the class's methods, starting with the constructor.

The class constructor

The __construct method runs every time we instantiate a new object. In our case the __construct method takes as an argument the filepath to the file that will store the users, which is the users.json file. We will see this later on.

 // Class Methods ------------
	public function __construct($json_file_path){
		$this->json_file = $json_file_path;
		$this->stored_users = json_decode(file_get_contents($this->json_file), true);
		$this->number_of_records = count($this->stored_users);

		if($this->number_of_records != 0){
			foreach ($this->stored_users as $user) {
				array_push($this->ids, $user['id']);
				array_push($this->usernames, $user['username']);
			}
		}
	}
  • Now as i said above the __construct method runs every time we instantiate a new object. In our case this will be...

    $user = new User("users.json");

    ... and the __construct($json_file_path) method will run.

  • In line 12 we take the incoming filepath, and assign it to the json_file property.

    $this->json_file = $json_file_path;

    To access the properties inside a class we use the keyword $this followed by the -> object operator, and then the property's name.

  • Next we fetch all the stored users from the json file with the file_get_contents() function, we decode them to a php array with the json_decode() function, and store them in the stored_users property.

    $this->stored_users = json_decode(file_get_contents($this->json_file), true);

    If there are no users in the file, the stored_users property will hold an empty array.
    Remember that we initiated the json file to an empty array.

  • Next in line 14 we count the users that the stored_users property holds, and store the number in the number_of_records property.

    $this->number_of_records = count($this->stored_users);
  • Next in line 16-21 we have an if statement.

    if($this->number_of_records != 0){
    	foreach ($this->stored_users as $user) {
    		array_push($this->ids, $user['id']);
    		array_push($this->usernames, $user['username']);
    	}
    }
    		

    We are gonna check the number_of_records property, and if the returned value is NOT zero, which means that we have users stored in the json file, we are going to loop through the stored_users property which is an array, and add every user's id in the id's array property, and all the usernames in the usernames array property.

    And we are done with the constructor method. All properties are going to be initialized with their values every time we create a new User object.

Adding the user's id field

Next and after the constructor, we are going to write a method named setUserId() to add a unique user id value before we insert the user in the json file. We will create an auto-increment id column like we have in a mysql database table.

	private function setUserId(array $user){
		if($this->number_of_records == 0){
			$user['id'] = 1;
		}else{
			$user['id'] = max($this->ids) + 1;
		}
		return $user;
	}
  • In line 23 we declaring the setUserId() method and we pass-in as an argument the user array. We are setting the scope to private, because there is no use of the method outside the Class.
  • In line 24 we are checking the number_of_records property, and if the returned value is zero...
  • ...we creating a new key=>value pair in the user array in line 25, named ['id'], and set the value to one, because this is the first entry.
  • Else in line 27 we use the max() function to get the highest value from the ids array, and assign it to the $user['id'] key.
  • And last in line 29, and outside the if statement we return the $user array which now holds the "username", "password", "status", and also the user id field.

Next we are going to write a private method which we will use several times inside our class, so we don't write repetitive code.

The storeData method

The storeData() method will insert the stored_users array back to the JSON file. Again we set the visibility scope to private.

	private function storeData(){
		file_put_contents(
			$this->json_file,
			json_encode($this->stored_users, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), 
			LOCK_EX
		);
	}
  • In line 32 we are declaring the storeData() method. The method doesn't take any arguments.
  • In line 33 we run the file_put_contents function.
  • In line 34 we have the functions first argument and that is the json's filepath.
  • Next in line 35 we have as the second argument the json_decode function, because we need to convert the stored_users array back to json, before we insert the data to the file.

    The json_decode function takes as a first argument the data that we want to convert, and as a second argument we pass-in some constants.

    The JSON_PRETTY_PRINT constant will structure the json data in the file like an array, and the JSON_UNESCAPED_UNICODE constant is used to display non Latin langauges like Cyrilic or Greek.

  • And in line 36 we have the third argument of the file_put_contents function which is the LOCK_EX constant. The LOCK_EX constant will lock the file while the function is writing the data to the file. This is a security mesure.

In the next method where we are going to insert the user in the file, we are going to use both private methods above so it will make sense to you.

Inserting the user in the file

Next we are going to write a method named insertNewUser() which will insert the user in the json file.

	public function insertNewUser(array $new_user){
		$user_with_id_field = $this->setUserId($new_user);
		array_push($this->stored_users, $user_with_id_field);

		/* Username validation */
		if($this->number_of_records == 0){
			$this->storeData();
		}else{
			if(!in_array($new_user['username'], $this->usernames)){
				$this->storeData();
			}else{
				return false;
			}
		}
	}
  • In line 40 we set the method's visibility scope to public, because we will call the method from the script.php file to insert the user. The method takes as an argument the user array.

    public function insertNewUser($new_user)
  • In line 41 we call the private method setUserId() and we pass-in the $new_user array.

    $user_with_id_field = $this->setUserId($new_user);

    The method will return a new array with the added id key=>value pair, which we are going to store it in the $user_with_id_field variable.

  • Next in line 42 we are going to add the $user_with_id_field array to the stored_users array property.

    array_push($this->stored_users, $user_with_id_field);
  • Now we are ready to write the data to the json file, but first we have to check if the username is available.

    So in line 45 we have an if statement. We are going to check the number_of_records property and if the value is zero, (which means there are no users in the file), we don't need to validate the username. So we inserting the data in the file using our private storeData() method in line 46.

    if($this->number_of_records == 0){
    	$this->storeData();
    }else{
    	if(!in_array($new_user['username'], $this->usernames)){
    		$this->storeData();
    	}else{
    		return false;
    	}
    }
    		

    Else if there are stored users in the file we will check if the new_users username is NOT in the usernames property and then store the data in the file. Line 48-49. In this way we will have unique usernames in our json file.
    If the username exists the method will return false;

Now let's test the insertNewUser() method and see all the above code in action.


Let's go back to the script.php file where we have the $new_user array and insert our friend Bob in the json file.

	$new_user = [
		"username" => "Bob",
		"password" => "7890",
		"status" => "active"
	];
	$user = new User("users.json");
	$user->insertNewUser($new_user);
  • In line 3 we have the $new_user array.
  • In line 8 we creating a new User object and we pass in the "users.json" file. We will store the returned object in the $user variable.
  • And in line 9 we use the $user variable to access and run the insertNewUser() method and we pass-in as an argument the $new_user.
  • If we run the code and open the json file we will see the data below. We see that the id field is added in the user.

    [
        {
            "username": "Bob",
            "password": "7890",
            "status": "active",
            "id": 1
        }
    ]		

  • Let's change the username to "George" and run the code again.

    	$new_user = [
    	"username" => "George",
    	"password" => "1234",
    	"status" => "active"
    	];
    	$user = new User("users.json");
    	$user->insertNewUser($new_user);
    		

  • We see that the user "George" is added in the json file and has an id of 2.

    [
        {
            "username": "Bob",
            "password": "7890",
            "status": "active",
            "id": 1
        },
        {
            "username": "George",
            "password": "1234",
            "status": "active",
            "id": 2
        }
    ]		

  • If we run the code again with the same username nothing will happen.

And we are done with the insertNewUser() method. Now lets see how we update a user.

Updating the User

Next we are going to write a function named updateUser(), which you already guessed will update the user's values in the file.

	public function updateUser($user_id, $field, $value){
		foreach($this->stored_users as $key => $stored_user){
			if($stored_user['id'] == $user_id){ 
				$this->stored_users[$key][$field] = $value;
			}
		}
		$this->storeData();
	}

  • In line 56 we have the updateUser() method which takes three arguments.
    public function updateUser($user_id, $field, $value)

    The first argument is the user's id which we are going to use, to target the user that we want to update.

    The second argument is the field, (or key) that we want to update, ie. the "username", the "password", or the "status".

    And the third argument is the new value we want to set.

  • In line 57 and inside the method we are going to use a foreach function to loop through the stored_users array property and fetch the keys and values.

    foreach($this->stored_users as $key => $stored_user)

    Remember that the stored_users array property holds all the users from the file every time we create a new object. Also the stored_users array is a two-dimensional array, this means that we have arrays inside an array.

    Let me show you how the stored_users array property looks like.

    <?php 
    array ( // this is the stored_users array
      0 => array ( // this user array has a key of 0
        'username' => 'Bob', 
        'password' => '7890',
        'status' => 'active',
        'id' => 1,
      ),
      1 => array ( // this user array has a key of 1
        'username' => 'George',
        'password' => '7890',
        'status' => 'active',
        'id' => 2,
      ),
    );
    ?>		

    Have in mind the structure of the stored_users array, and the following code will be very easy to understand.


  • Inside the loop we will have an if statement that will check if a $stored_user['id'] has the same value as the given $user_id argument. Line 58.

    if($stored_user['id'] == $user_id){
  • If there is a match we will target the users field, and set the new value in line 59.

    	$this->stored_users[$key][$field] = $value;
    	// If we hard-code the line above it will look something like this.
    	$this->stored_users[0]["status"] = "blocked";
    		
  • And in line 62 we use the storeData() method to store the updated data back to the json file.

    $this->storeData();

Now let's go back again to the script.php file and update a user to test the code.

$user = new User("users.json");
$user->updateUser(1, 'status', 'blocked');
  • In line 8 we creating the User object and pass in the constructor the "users.json" filepath.
  • In line 9 we are calling the updateUser() method and we pass-in the arguments that the method need. The method takes as the first argument the user's id, second argument the field, and third argument the new value. In short here we are saying, find user with "id=1", and change the "status" to "blocked".
  • If we run the code we will see in the json file the below results.
    We see in line 5 that the status for the user Bob is changed to "blocked".
    [
        {
            "username": "Bob",
            "password": "7890",
            "status": "blocked",
            "id": 1
        },
        {
            "username": "George",
            "password": "1234",
            "status": "active",
            "id": 2
        }
    ]
    		

And we are done with the updateUser() function. Now let's see how we delete a user from the json file.

Deleting a user

To delete a user we are going to write the deleteUser() method. The method takes as an argument the id of the user we want to delete from the file.

	public function deleteUser($user_id){
		foreach($this->stored_users as $key => $stored_user){
			if($stored_user['id'] == $user_id){
				unset($this->stored_users[$key]);
			}
		}
		$this->storeData();
	}

We have here the same logic as we had with the updateUser() method.

We are going to loop again through the strored_users array property, and we are going to search for the given $user_id. If there is a match we are going to unset the users $key and this will remove the whole user array from the stored_users.

And in line 71 we store the updated data to the json file.

Let's go back to the script.php file, and let's delete the user with id 1, which is Bob.

$user = new User("users.json");
$user->deleteUser(1);
  • In line 8 we creating a new User object, and we pass in the constructor the json file's filepath.
  • And in line 9 we run the deleteUser() method, and pass-in as an argument the users id.
  • If we run the code we will see in the json file that we have only one user in the file. Our friend Bob is gone.
    [
    	{
    	    "username": "George",
    	    "password": "1234",
    	    "status": "active",
    	    "id": 2
    	}
    ]
    	

And we are done with the deleteUser() method. Now lets see how to delete all users from the json file.

Delete all users from file

For this task we are going to write the deleteAllUsers() method.

	public function deleteAllUsers(){
		foreach ($this->stored_users as $key => $value) {
			unset($this->stored_users[$key]);
		}
		$this->storeData();
	}

The logic is here simple we are going to loop through the stored_users array property and unset every user array key. This will remove every user from the file. After removing all users, we are left with an empty array. But still we have to write the empty array to the file.

So in line 78 we write the empty array to the json file.

If we run the code...

$user = new User("users.json");
$user->deleteAllUsers();

...we will see an empty array in the json file.

[]

And we are done with the deleteAllUsers() method. Now lets go and write our last method to get the users from the file

Get users from file

To get the users from the json file we are going to write a function named getUsers(). Now this is really an easy one. We just have to return the stored_users array property.

	public function getUsers(){
		return $this->stored_users;
	}
} // End of User class	

This time we don't only execute the method, but we have to store the returned data to a variable.

$user = new User("users.json");
$users = $user->getUsers();

Now the $users variable is holding all users from the json file, if there are no users in the file the $users variable is holding an empty array.

And that's it, we completed the User Class and this tutorial.

Summary

In this tutorial we saw how to insert, update, and delete, users in a JSON file.

Last Words

Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any error's, so i can update the page with the correct code.

Source code

You can download the source code and use it in any way you like.

Times downloaded: 324

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal

Comment section

You can leave a comment, it will help me a lot.

Or you can just say hi. 😉