douyong8801 2017-04-17 05:30
浏览 27
已采纳

Codeigniter查询生成器更新功能

I have an update function in my Model which I call from My controller as

if($_POST)
{
   $this->User_model->update('user_about',$_POST,$this->session->userdata['id']);
}

takes three parameters, table name, post data and user id. The function is defined in the Model as

public function update($table,$data,$id)
{
    $row=$this->db->select('*')->from($table)->WHERE('user_id',$id)->row();
    if($row)
    {
        $this->db->WHERE('user_id',$id)->UPDATE($table,$data);
    }
    else
    {
        $data['user_id']=$id;
        $this->db->insert($table,$data);
    }
}

What I am doing here is checking if the record of particular user doesn't exist it should insert, otherwise update. Works like a charm

Question

Is there a way to skip the IF condition block?. Is there any provision in query builder which performs the check itself?

  • 写回答

1条回答 默认 最新

  • douzhang3822 2017-04-17 08:13
    关注

    Here is a custom generic insert and update on duplicate function that I always used in my programming.

    public function updateOnDuplicate($table, $data ) 
       {
         if (empty($table) || empty($data)) return false;
         $duplicate_data = array();
    
         foreach($data AS $key => $value) {
            $duplicate_data[] = sprintf("%s='%s'", $key, $value);
         }
    
         $sql = sprintf("%s ON DUPLICATE KEY UPDATE %s", $this->db->insert_string($table, $data), implode(',', $duplicate_data));
    
         $this->db->query($sql);
         return $this->db->insert_id();
       }
    

    You can use the above function in the model and call it in the controller. The function will update the value if the duplicate occurs. Check out following blog post if you need detail explanation A Generic CodeIgniter Function for both Update and Insert.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?