【问题标题】:Codeigniter inserts empty value, default value of table field in MySQL is ignoredCodeigniter插入空值,MySQL中表字段的默认值被忽略
【发布时间】:2012-06-29 11:56:03
【问题描述】:

我正在插入一个表,一些数据是空的,所以我希望一些字段得到我分配的默认值。

$data = array(
            'id'            => $id,
            'user'       => $this->input->post('name'),
            );

$this->the_model->the_model_funciton($data);

问题在于用户字段,该字段的默认值为“匿名”,但是当 post('name') 中没有数据时,会插入一个空值而不是该字段中的默认值。

用户字段为 varchar,null。

【问题讨论】:

    标签: php mysql codeigniter default


    【解决方案1】:

    这样可以吗?

    $data = array(
               'id'   => $id
           );
    
    if ($user = $this->input->post('name')) {
       $data['user'] = $user;
    }
    

    【讨论】:

    • 我收到错误“无法在第 xx 行的写入上下文中使用方法返回值”
    • @Alex,我仍然看到一个空值被插入,而不是默认字段值:-(
    • 成功了 :) 但是假设我有 10 或 20 个字段也需要获取默认值,我需要为每个输入执行此操作吗?这是 Codeigniter 中 post 方法的正常行为吗?
    • @Danny: TBH 我从来没有使用过 CodeIgniter :) 如果通过 NULL 不起作用,很遗憾,这可能是你唯一的选择。
    【解决方案2】:

    这可能与post 方法有关。当name 为空或未定义时,它将返回一个空字符串。然后在列中输入。

    【讨论】:

      【解决方案3】:

      试试这个

      $default_user = "Anon";
      $username = $this->input->post('name');
      if($username == empty) ? $username = $default_user : $this->input->post('name'));
      $data = array(
                  'id'            => $id,
                  'user'       => $this->input->post('name'),
                  );
      
      $this->the_model->the_model_function($data);
      

      【讨论】:

      • if(empty($username)) ? $username = $default_user : $this->input->post('name'));
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 2013-11-05
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      相关资源
      最近更新 更多