CodeIgniter Forums
How handle errors when inserting data? - 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: How handle errors when inserting data? (/showthread.php?tid=79742)



How handle errors when inserting data? - lelolenda - 07-25-2021

Error dump:

mysqli_sql_exception #1062
Duplicate entry 'john' for key 'users.username'

A part of my code:

Code:
$dataUser = [
'username' => $request->getPost('username'),
'email'    => $request->getPost('email'),
'password' => md5($request->getPost('password'))
];

$userModel = new UserModel();

$userModel->insert($dataUser);



RE: How handle errors when inserting data? - brabus - 07-25-2021

Here is my example, if you have any questions, feel free to ask. https://pastebin.com/et677dB5

Hope it will help a little bit.


RE: How handle errors when inserting data? - lelolenda - 07-26-2021

(07-25-2021, 09:02 PM)brabus Wrote: Here is my example, if you have any questions, feel free to ask. https://pastebin.com/et677dB5

Hope it will help a little bit.
helped, but it would help more if it were possible to do this with an if, I just read in the documentation that the save or insert methods return false when they fail


RE: How handle errors when inserting data? - InsiteFX - 07-26-2021

use a try catch block


RE: How handle errors when inserting data? - ikesela - 07-26-2021

use validation, for your case: duplicated username entry
use this rules:

'username' => 'required||is_unique[users.username]' // usename already exist in db

or

'username' => 'is_not_unique[users.username]' // username not exist in db


give validation error if username already exist or not


RE: How handle errors when inserting data? - paliz - 07-26-2021

If has any error but you have set validation rule in model
If(! $model-save($data)){
$model->errors;
}


RE: How handle errors when inserting data? - wuuyun - 07-26-2021

also can use $res = $this->db->error(); echo $res['message'];
in model