CRUD (Create, Read, Update, Delete) operations are fundamental in web development, allowing you to manage data efficiently. PHP, a versatile server-side scripting language, can be used to perform these operations on data stored in a JSON file. JSON (JavaScript Object Notation) is a lightweight data-interchange format that's easy to work with. In this example, we'll demonstrate how to perform CRUD operations using PHP and a JSON file.
Example:
Step 1: Reading Data
To get started, you'll need PHP and a JSON file. Let's assume you have a JSON file named data.json that contains an array of records. To read this data, you can use the following PHP code:
$jsonData = file_get_contents('data.json');
$data = json_decode($jsonData, true);
In this code:
file_get_contents('data.json')
reads the JSON file.json_decode($jsonData, true)
converts the JSON data into a PHP array for manipulation.
Step 2: Creating Data
To create new records, you prepare an array with the data and append it to the existing JSON array. Here's how you can create a new record with an example:
$newData = ['id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com'];
$data[] = $newData;
file_put_contents('data.json', json_encode($data));
In this code:
- We define a new record as an associative array.
- The new record is added to the existing data array.
file_put_contents('data.json', json_encode($data))
saves the updated data back to the JSON file.
Step 3: Updating Data
To update existing data, you locate the record you want to change, modify its values, and rewrite the JSON file with the updated data. Here's an example of updating a record:
foreach ($data as &$record) {
if ($record['id'] == 1) {
$record['name'] = 'Updated Name';
}
}
file_put_contents('data.json', json_encode($data));
In this code:
- We loop through the data array and find the record with a specific
id
. - If the record matches, we update its
name
field. - The updated data is saved back to the JSON file.
Step 4: Deleting Data
To delete a record, you filter out the unwanted record from the JSON data and save the remaining data back to the file. Here's an example of deleting a record:
$data = array_filter($data, function ($record) {
return $record['id'] != 1;
});
file_put_contents('data.json', json_encode(array_values($data)));
In this code:
- We use
array_filter
to remove the record with a specificid
. array_values($data)
re-indexes the array to ensure continuous numeric keys.- The modified data is saved back to the JSON file.
Conclusion
Performing CRUD operations with PHP and a JSON file is a practical way to manage data in web applications. By following this example and applying it to your projects, you'll gain a valuable skill for creating, updating, and deleting data efficiently.