I am running this function to delete the records from the database. I received the message in response as ‘successfully deleted’, but the records are not deleted from the database table.
public function deleteInventory()
{
$token = $this->request->getPost('token');
$dateReceived = $this->request->getPost('date');
if ($token) {
$resultarray = validateToken($token);
if ($resultarray['success'] == 'True') {
try {
$stocktable = new InventoryStock();
$builder = $stocktable->builder();
// Fetch records based on the date received
$records = $builder->where('date_received', $dateReceived)->findAll();
// Check if records exist
if (!empty($records)) {
// Array to hold the IDs
$ids = [];
// Loop through and collect IDs
foreach ($records as $record) {
// Check if $record is an object or array
if (is_array($record)) {
$ids[] = $record['id'] ?? null; // Safe access for array
} elseif (is_object($record)) {
$ids[] = $record->id ?? null; // Safe access for object
}
}
// Delete records based on collected IDs
$deletedCount = $builder->whereIn('id', $ids)->delete();
if ($deletedCount) {
// Successful deletion
return json_encode([
"success" => "True",
"message" => $deletedCount . " records deleted successfully.",
"ids" => $ids
]);
} else {
// No records deleted
return json_encode([
"success" => "False",
"message" => "Deletion failed or no records were deleted."
]);
}
}
} catch (Exception $e) {
return json_encode(["error" => "Exception", "message" => $e->getMessage()]);
}
} else {
return json_encode($resultarray);
}
} else {
return json_encode(["error" => "Exception", "message" => "Token Missing"]);
}
}
The response message shows “records deleted successfully”, but in the database the records still exist.
3