I’m using CodeIgniter v4.4.1. I’m trying to insert Customers into my MySQL database. My Customer table has only two columns for now (for testing): idcustomer
(primary key, not null, auto increment), and name
(varchar(45)). That’s working fine.
My Customer
model looks like this:
<?php namespace AppModels;
use CodeIgniterModel;
class Customer extends Model
{
protected $table = 'customers';
protected $primaryKey = 'idcustomer';
protected $returnType = 'array';
protected $useTimestamps = false;
protected $allowedFields = ['name'];
}
In my controller,
<?php
namespace AppControllers;
use AppControllersBaseController;
// use CodeIgniterController;
use AppModelsCustomer;
class CustomerController extends BaseController
{
//...
public function store()
{
$customerData = $this->request->getPost();
// return view('customer/test', $customerData);
// I used this line above to test if I had any data in $customerData, and I was able to access the data from the post request there. So up to here, everything is working fine.
$customer = model('Customer');
$customer->save([
'name' => $customerData['name'],
]);
return redirect()->to('/customers');
}
//...
}
When I submit a form, the post request is submitted successfully, and I am even redirected to the /customers
route (as indicated in the controller’s store()
method. However, when I check my database, the new customer is not inserted. The database remains the same as it was before… I would have expected the new record to be created in the customer table.
I removed all validation to test, and it still is not working. I am not getting any errors, exceptions, or anything in the writable/logs.
So, I tried doing this in my controller:
public function store()
{
$customerData = $this->request->getPost();
$customer = model('Customer');
$customer->save([
'idcustomer' => 22, // that is, an ID number that does not exist yet in my database (the highest existing ID is 5)
'name' => $customerData['name'],
]);
return redirect()->to('/customers');
}
When I submit the form again, now a new entry is created, but, it is created with the idcustomer
= 6.
Now, when I do:
$customer->save([
'idcustomer' => 3, // an existing ID
'name' => $customerData['name'],
]);
Then, the entry with idcustomer = 3
is modified (as expected).
I also tried the $customer->insert(...)
and it’s not working either.
So, bottom line, my question is, why is a new record not inserted into the database when I do not pass in the idcustomer
?
2
Answers
Try to change it like this:
You have to set this in your model-file (if this represents your db-schema) or you have to explicitly provide the primary key for every query.