I was trying to delete the JSON entry from the JSON file while clicking a button that is in an HTML tableenter image description here
and my JSON data:[{"room_id":"1","room_type":"Duplex","room_location":"North","room_charge":"45","room_status":"available","payment_status":"not paid"},{"room_id":"2","room_type":"Singlex","room_location":"South","room_charge":"54","room_status":"available","payment_status":"not paid"},{"room_id":"3","room_type":"Duplex","room_location":"East","room_charge":"45","room_status":"available","payment_status":"not paid"},]
and here is my code for creating the table part
<div class="table-responsive">
<table class="table table-striped table-dark">
<tr>
<th>Room ID</th>
<th>Room Type</th>
<th>Room Location</th>
<th>Room Charge</th>
<th>Room Status</th>
<th>Payment Status</th>
<th>Update</th>
<th>Delete</th>
</tr>
<?PHP
$data = file_get_contents("room-data.json");
$data = json_decode($data, true);
foreach($data as $row)
{
echo '<form action="" method="post">
<tr>
<td name="room_id">'.$row["room_id"].'</td>
<td name="room_type">'.$row["room_type"].'</td>
<td name="room_location">'.$row["room_location"].
'</td><td name="room_charge">'.$row["room_charge"].'</td>
<td name="room_status">'.$row["room_status"].'</td>
<td name="payment_status">'.$row["payment_status"].'</td>
<td name="update">'."Update".'</td>
<td><button type="submit" name="delete">'."Delete".'</button></td>
</tr>
</form>';
}
?>
</table>
</div>
So when I will click on the button the respective JSON data for that delete button will also delete and I want to do that using PHP
How can I do that?
My Answer:
To delete the JSON entry from the JSON file using PHP when clicking on a button in the HTML table, you can modify your code as follows:
1. Add a hidden input field in the form to store the room_id of the entry to be deleted.
2. Check if the form is submitted and the delete button is clicked.
3. If the delete button is clicked, loop through the JSON data and remove the entry with the matching room_id.
4. Encode the updated JSON data and write it back to the JSON file.
Here is the updated code:
php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = file_get_contents("room-data.json");
$data = json_decode($data, true);
if (isset($_POST['delete'])) {
$deleteRoomId = $_POST['room_id'];
foreach ($data as $key => $row) {
if ($row['room_id'] == $deleteRoomId) {
unset($data[$key]);
break;
}
}
$data = array_values($data); // Re-index the array
file_put_contents("room-data.json", json_encode($data));
}
}
$data = file_get_contents("room-data.json");
$data = json_decode($data, true);
foreach ($data as $row) {
echo '';
}
?>
In this code, when the delete button is clicked, the corresponding room_id is passed to the PHP script. The script then removes the entry with that room_id from the JSON data and updates the JSON file.
Rate this post
5 of 5 based on 2921 votesComments