如果查询没有更新

时间:2014-09-24 09:47:02

标签: php codeigniter

我想知道将查询转换为if语句的最佳方法。因为我想为我的codeigniter编辑主函数使用一个函数,

所以它结合了两个查询并且如果查询不是更新则使它成为插入方式是最好的方式

public function addUserGroup($data) {
    $this->db->query("INSERT INTO " . $this->db->dbprefix . "user_group SET 
    name = " . $this->db->escape($data['name']) . ", 
    permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') . " ");
}

public function editUserGroup($user_group_id, $data) {
    $this->db->query("UPDATE " . $this->db->dbprefix . "user_group SET 
    name = " . $this->db->escape($data['name']) . ", 
    permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') . " WHERE user_group_id = '" . (int)$user_group_id . "'");
}

3 个答案:

答案 0 :(得分:0)

尝试在变量中保存值并将var传递给查询并尝试向查询变量添加适当的引用

public function addUserGroup($data) {
  $perm = (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '');
  $this->db->query("INSERT INTO " . $this->db->dbprefix . "user_group SET name = '" . $this->db->escape($data['name']) . "', permission = '" .$perm. "' ");

}

答案 1 :(得分:0)

你可以用一个非常简洁的查询来做到这一点:

"INSERT INTO " . $this->db->dbprefix . "user_group SET name = " . 
$this->db->escape($data['name']) . ", 
permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') . 
" ON DUPLICATE KEY UPDATE ". 
$this->db->dbprefix . "user_group SET name = " . 
$this->db->escape($data['name']) . ", 
permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') . " 
WHERE user_group_id = '" . (int)$user_group_id . "'");

唯一需要的是表格上的主键

答案 2 :(得分:0)

您可以使用" user_group_id"设置if / else条件。我认为这必须来自像$this->input->post('user_group_id')这样的帖子数组。

所以你可以创建一个函数来检查这些条件,如下所示:

function my_function(){
   if($this->input->post('user_group_id')){
    // call update query
   }else{
    // call insert query
   }
}