Welcome Guest, Not a member yet? Register   Sign In
How handle errors when inserting data?
#1
Question 

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);
Reply
#2

(This post was last modified: 07-25-2021, 09:03 PM by brabus.)

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

Hope it will help a little bit.
Reply
#3

(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
Reply
#4

use a try catch block
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#5

(This post was last modified: 07-26-2021, 09:41 AM by ikesela.)

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
Reply
#6

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

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




Theme © iAndrew 2016 - Forum software by © MyBB