Search code examples
exceptioninsertcodeigniter-4

cannot insert data in codeigniter 4


I want to insert registration data, I followed the existing tutorial, but got an error exception.

$users = new UsersModel();
$data = [
    'name' => $this->request->getPost('name'),
    'email' => $this->request->getPost('email'),
    'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT) 
];

$users->insert($data);

My Model:

<?php 

namespace App\Models;

use CodeIgniter\Model;

class UsersModel extends Model
{
    protected $table = "users";
    protected $primarykey = "id";
    protected $returnType = "object";
    protected $useTimestamps = true;
    protected $allowedFields = ['name', 'email', 'password'];
}

throw the exception:

mysqli_sql_exception #1054

Unknown column 'updated_at' in 'field list' 

Solution

  • The exception is

    mysqli_sql_exception #1054
    
    Unknown column 'updated_at' in 'field list' 
    

    Which strongly suggests that it is expecting a column called updated_at.

    You have set protected $useTimestamps = true;

    So as per the documentation:

    $useTimestamps

    This boolean value determines whether the current date is automatically added to all inserts and updates. If true, will set the current time in the format specified by $dateFormat. This requires that the table have columns named ‘created_at’ and ‘updated_at’ in the appropriate data type.

    So you need to create the columns created_at and updated_at