Welcome Guest, Not a member yet? Register   Sign In
Database model insert always returns 0

Hi guys,

My model always seems to return 0 after doing an insert, despite the insert succeeding. Looking at the CI code, I would have thought it returns the insert id. What am I doing wrong?

PHP Code:
class UserModel extends BaseModel {
protected $table 'myusertable';
    protected $primaryKey 'uid';
protected $allowedFields = ['uid''username'];

    protected $returnType = \App\Entities\User::class;
    protected $useTimestamps true;

$data = [
'uid' => '123',
'username' => 'joe'

does the uid field have a primary key and is it auto-incrementing?

(This post was last modified: 02-23-2022, 08:44 AM by Gary.)

Try calling it like this:

$model->insert($data, TRUE);      // insertID is returned by an insert/modify/save/update function

Thanks guys for your comments.

It lead me to recheck the CI Model/BaseModel code and realised it will only return the insert ID for auto-incrementing primary keys.

In my case, uid was not auto-incrementing so I had to pass FALSE as the second parameter to insert() to get it to return a bool instead.

I don't think any of this is documented in the User Guide. If it has been mentioned, please let me know where I can find it for future reference. Thanks!

Although CI has a lot of documentation, I find it's not particularly detailed... which means looking at the system code to work out what's happening under the bonnet when one wants to do anything more involved than the basic examples in the documentation.

Of course, as this is "undocumented" usage, it is possible that the functionality one deduced (and has used in one's code) may change in the future... perhaps more of an issue in the initial releases of CI 4, but hopefully becoming less likely now that its matured a bit (?).

(This post was last modified: 02-24-2022, 01:29 AM by InsiteFX.)

insert([$set = null[, $escape = null]])

$set (array) – An associative array of field/value pairs
$escape (bool) – Whether to escape values

true on success, false on failure

Return type:

Compiles and executes an INSERT statement.

What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )

Theme © iAndrew 2016 - Forum software by © MyBB