2016-03-08 57 views
1

我是一般的CodeIgniter和PHP的新手。我用一些非空列创建了一个新表。非空列都根据其数据类型设置了默认值,因此VARCHAR具有空字符串,而数字类型的默认值为0。将缺省值留空的非空列为空时会出现MySQL错误1366

但是,一旦我填写表格(在这里我故意留下非空列留空,以测试它们),并点击提交按钮,它提供了以下错误:

Error Number: 1366

Incorrect integer value: '' for column 'salary' at row 1

它插入当发现用户没有输入任何值时,为空字符串添加双引号。我检查了检查mysql模式,它被转到严格模式。但是,因为我使用的是多租户数据库(Azure-clearDB),他们不会允许我超级特权,并且我无法关闭严格模式(或者我可以吗?)

有没有办法关闭此模式,或者还有其他解决方法吗?我不想为每列明确添加一个SQL if-else子句,因为这会被硬编码。请帮助 的代码如下:

控制器:

$additional_data = array(
       'first_name' => $this->input->post('first_name'), 
       'last_name'  => $this->input->post('last_name'), 
       'phone'   => $this->input->post('phone'), 
       'salary'  => $this->input->post('salary')); 

if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email, $additional_data)) 
     { 
     $identity = $this->ion_auth->where('email', strtolower($this->input->post('email')))->users()->row(); 
     $forgotten = $this->ion_auth->forgotten_password($identity->{$this->config->item('identity', 'ion_auth')}); 
     $this->session->set_flashdata('message', $this->ion_auth->messages()); 
     redirect('auth/success', 'refresh'); 

MODEL:

//filter out any data passed that doesnt have a matching column in the users table 
    //and merge the set user data and the additional data 
    $user_data = array_merge($this->_filter_data($this->tables['users'], $additional_data), $data); 

    $this->trigger_events('extra_set'); 

    $this->db->insert($this->tables['users'], $user_data); 

    $id = $this->db->insert_id(); 

    //add in groups array if it doesn't exits and stop adding into default group if default group ids are set 
    if(isset($default_group->id) && empty($groups)) 
    { 
     $groups[] = $default_group->id; 
    } 

    if (!empty($groups)) 
    { 
     //add to groups 
     foreach ($groups as $group) 
     { 
      $this->add_to_group($group, $id); 
     } 
    } 

    $this->trigger_events('post_register'); 

    return (isset($id)) ? $id : FALSE; 

UPDATE:我插入多​​个列的值具有相同的INSERT语句。

+0

也显示代码。 –

+0

绝对包括你的代码在问题中。它对调试有很大的帮助。我在这里猜测,但它听起来像你把任何值插入到表单中,并直接注入数据库。这通常是不好的做法,你需要在输入数据库之前对输入进行清理和验证。否则,它为SQL注入和攻击留下了空间。 – khuderm

回答

0

根据您的描述,您已将列'salary'设置为一个整数列,但是您插入''作为空字符串。

因此您需要在'salary'列中设置0而不是''

+0

我在视图中通过将attr值设置为0来做到这一点。但我不确定这是否是很好的编码实践(即更改视图)。我宁愿在缺少值的情况下插入默认值(即0),因为严格模式无法关闭 – omrakhur

+0

实际上,视图是选择查询语句,我们不能直接向它们中插入数据,而是在表中插入数据。根据你的更新,如果你只是在你的表格中插入'$ additional_data',你可以预先处理'salary'。 ''salary'=>(isset($ this-> input-> post('salary'))&&(int)$ this-> input-> post('salary'))?(int)$ this-> input - > post('salary'):0' –

+0

好的,这样做更有意义!谢谢! – omrakhur