2014-10-07 79 views
0

我试图插入到我的数据库表中。如果值为空,则使用默认字段将CI插入数据库中

我从列收到此错误:

Column 'allow_edit_time_due' cannot be null 

但是,列被设置为默认值:“0”

我如何才能插入我的表,如果“allow_edit_time_due”为空,这样的值是默认值?

查询:

$sql = "INSERT INTO `cal_tasks` (user_id, task, task_notes, task_type, allow_edit_time_due, task_time_due, user_created) VALUES (" . $this->db->escape($user_id) . ", " . $this->db->escape($data['task']) . ", " . @$this->db->escape($data['task_notes']) . ", " . @$this->db->escape($data['task_type']) . ", " . @$this->db->escape($data['allow_edit_time_due']) . ", " . $this->db->escape($data['task_time_due']) . ", " . @$this->db->escape($data['user_created']) . ")"; 
+0

什么是您的插入是什么样子? – Hammerstein 2014-10-07 15:48:46

+0

用查询更新 – 2014-10-07 15:50:55

+0

在你的$ data中,$ data ['allow_edit_time_due']是什么样的?如果它没有被设置,即它是空的,那么你将试图将它设置为空。默认仅在您未指定列时生效。因此,要么从插入中删除列(因为它有默认值,请确保)或确保$ data ['allow_edit_time_due']不能设置为空。 – Hammerstein 2014-10-07 15:53:34

回答

0

正如你已经发现,传递NULL值的SQL将尝试以填补NULL值之列,这会导致错误。

无论如何,使用活动记录将有助于简化您的代码(如果可取的话)在这个问题上。所有的值都会自动转义。

这是一个例子:

$cal_task = array(
    'user_id' => $user_id, 
    'task' => $data['task'], 
    'task_notes' => $data['task_notes'], 
    'task_type' => $data['task_type'], 
    'task_time_due' => $data['task_time_due'], 
    'user_created' => $data['user_created'] 
); 

// optional, default if null 
if (isset($data['allow_edit_time_due'])) 
{ 
    $cal_task['allow_edit_time_due'] = $data['allow_edit_time_due']; 
} 

$this->db->insert('cal_tasks', $cal_task); 
相关问题