【问题标题】:MySQL error 1366 appears when leaving non-null columns with default values as blank将具有默认值的非空列保留为空白时出现 MySQL 错误 1366
【发布时间】:2016-03-08 15:25:09
【问题描述】:

总的来说,我是 CodeIgniter 和 PHP 的新手。我用某些非空列创建了一个新表。非空列都根据其数据类型设置了默认值,因此 VARCHAR 有一个空字符串,而数字类型的默认值为 0。

但是,一旦我填写了表单(我故意将非空列留空以测试它们)并点击提交按钮,它会给出以下错误:

错误号:1366

不正确的整数值:第 1 行的列 'salary' 的 ''

当它发现用户没有输入任何值时,它正在为一个空字符串插入双引号。我检查了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');

型号:

    //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;

更新:我正在使用相同的插入语句插入多个列值。

【问题讨论】:

  • 一定要在问题中包含您的代码。它对调试有很大帮助。我在这里猜测,但听起来您将插入表单的任何值直接注入数据库。这通常是不好的做法,您需要在将输入放入数据库之前对其进行清理和验证。否则,它就会为 SQL 注入和攻击留下空间。

标签: php codeigniter azure mysql-5.5 cleardb


【解决方案1】:

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

因此您需要在“工资”列中设置0 而不是''

【讨论】:

  • 我已经在视图中做到了这一点,将值 attr 设置为 0。但我不确定这是否是好的编码实践(即更改视图)。我宁愿在缺少值的情况下插入默认值(即 0),因为无法关闭严格模式
  • 其实视图是select查询语句,我们不能直接往里面插入数据,而是表。并且根据您的更新,如果您只是将$additional_data 插入到您的表中,您可以预先设置salary,例如'salary' => (isset($this->input->post('salary'))&&(int)$this->input->post('salary'))?(int)$this->input->post('salary'):0
  • 好吧,这更有意义!谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
相关资源
最近更新 更多