Why inserting only one column to mysql database not show an error in codeigniter?

530 views Asked by At

UPDATE:

Because the answers already given, I make a testing with fresh installation of CodeIgniter 3.1.11.

And make a new database and table, with 3 columns: id, name, email.

Then, I try to insert the data using mysql cli:

INSERT INTO users (name) VALUES ('hikki bocchi')
--- result ---
ERROR 1364 (HY000): Field 'email' doesn't have a default value

Then, I try using CodeIgniter:

--- first code ---
$query = "INSERT INTO users (name) VALUES ('hikki bocchi')";
$this->db->query($query);
--- second code ---
$this->db->insert('users', ['name' => 'hikki bocchi']);

The result using first code or second code are the same:

the data inserted to the database with name = 'hikki bocchi' and email = '' (blank).

Is this bug on CodeIgniter? Or this only happens on me?

OLD:

First I'm new to CodeIgniter and Database, so I want to get easy to understand answer. I use CodeIgniter and MySQL, and I set the database using Adminer.

I created 8 columns: id, name, email, password, role_id, is_active, date_created, and date_modified.

database columns

And then I try to insert only 1 column (name) with codeigniter, and it show no error.

$this->db->insert('users', ['name' => 'Hikki Bocchi']);

My logic is, the value of column id, date_created, date_modified will created automatically, but the column name, email, password, role_id, is_active are not.

But why the data can inserted with only one column? Isn't this must be an error? The name value has inserted, and other columns value are blank or 0.

blank value

My question is why this can happen? And can't it show an error?

1

There are 1 answers

1
Blue On

MySQL has default values. When you use codeignier, it will rewrite that insert statement to something similar to:

INSERT INTO `users` (name) VALUES ('Hikki Bocchi');

From that point on, it's entirely up to your database to determine what the default values are. Use:

SHOW CREATE TABLE `users`;

to view what your current default values are. You can edit the schema, and change what the default values should be.