Php 如果值为null,则使用默认字段将CI插入数据库

Php 如果值为null,则使用默认字段将CI插入数据库,php,codeigniter,Php,Codeigniter,我正试图插入到我的数据库表中 我从列中获取此错误: Column 'allow_edit_time_due' cannot be null 但是,该列设置为默认值:“0” 如果'allow\u edit\u time\u due'为空,那么该值是默认值,我如何才能插入到我的表中 查询: $sql = "INSERT INTO `cal_tasks` (user_id, task, task_notes, task_type, allow_edit_time_due, task_time_due

我正试图插入到我的数据库表中

我从列中获取此错误:

Column 'allow_edit_time_due' cannot be null
但是,该列设置为默认值:“0”

如果'allow\u edit\u time\u 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']) . ")";

正如您所发现的,将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);

插入内容是什么样子的?在$data中,$data['allow\u edit\u time\u due']是什么样子的?如果它没有被设置,也就是说,它是空的,那么您将尝试将它设置为空。默认值仅在未指定列时生效。因此,要么从insert中删除该列(因为它是默认的),要么确保$data['allow\u edit\u time\u due']不能设置为null。我理解,谢谢。因此,如果我想在不提供$data['allow_edit_time_due']数据的情况下执行此操作,我需要大量条件来修改查询?我觉得应该有一种更简单的方法来做到这一点,而不会让我的代码看起来很糟糕。如果你不想包含$data['allow_edit_time_due']数据,那么你可以创建一个数组,其中的值在中,给索引一个列的名称,这些值就是要放入列中的值,然后说如果设置了$data['allow_edit_time_due']{$some_array['allow_edit_time_push']=>$data[allow_edit_time_push]然后使用内置的CI功能对其进行更新($this->db->update('您正在使用的表',$some_array)}$data[allow_edit_time_due])转到phpmyadmin结构并设置该列的默认值。。