php - 如何在 codeigniter 中使用插入或替换

标签 php mysql codeigniter

 public function save($data, $id)
    {
      $this->db->insert OR REPLACE($this->table, $data);
      return $this->db->insert_id();
    }

如果数据不存在则插入,否则数据存在则替换

最佳答案

试试这个

Check Unique data filed to check where record exist

public function save($data, $id)
{
    $query = $this->db->query("SELECT * FROM table_name WHERE id = '{$data['id']}' ");
    $result = $query->result_array();
    $count = count($result);

    if (empty($count)) {

        $this->db->insert('mytable', $data); 
    }
    elseif ($count == 1) {
        $this->db->where('id', $data['id']);
        $this->db->update('mytable', $data); 
    }
}

关于php - 如何在 codeigniter 中使用插入或替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34241942/

相关文章:

mysql - SQL中对列的操作

php - 我可以将 Ion auth 设置为通过用户名或电子邮件登录吗

php - 在 PHP 中,如何将过程代码包装在类中?

PHP 5.3 似乎默认缺少 Intl 扩展名

mysql - 在查询范围内使用()过滤

mysql - 需要帮助优化比较两个表的 mysql 查询

php - 如何将数据数组从模型传递到 Controller ,然后再传递回模型?

php - Codeigniter 链式查询问题

php - 如何简单地更新 mysql 中的特定时间戳?

php - MySQL 中的行明智 SUM 与列明智 SUM