CodeIgniter Forums
Get error save db in method Controller - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Get error save db in method Controller (/showthread.php?tid=75925)



Get error save db in method Controller - PHS - 03-29-2020

Hello friends!

In my controller I have the call to a model and the method to save the data received in the respective model:

PHP Code:
$my_model = new MyModel();

$my_model->save($data); 


I would like to know how I can handle an exception if something goes wrong in inserting the data into the table without stopping the system from running?

What happens is that I am testing and simulating database errors. I want to handle this error and show the user a message.

For example, if for some reason an error occurs in sending a mandatory field to the table and this data is being sent empty, I want to handle the exception and send a personalized message to the user instead of showing a message from CI4.

I've tried using try catch, affectedRows () and error () but it didn't work.


PHP Code:
if(!$my_model->save($data)) {
    return $message;
}

try {
    $my_model->save($data);
} catch (
Exception $e) {
    return $message;
}
if (
$my_model->save($data)->affectedRows() < 1) {
    return $message;
}

if (
$my_model->save($data)->error() !== null) {
    return $message;



None of these codes worked for the case.

I want to handle this in the controller.

How to make?