当我更新数据库设置表codeigniter上的行时。如果我只是更新一个项目,那么它会将每一行更改为已更新的那一行。如果我使用INSERT INTO它可以,但宁愿使用更新。
它应该只更新一个已更新的。
模型
<?php
class Model_setting extends CI_Model {
public function editSetting($group, $data, $website_id = 0) {
//$this->db->query("DELETE FROM " . $this->db->dbprefix . "setting WHERE website_id = '" . (int)$website_id . "' AND `group` = " . $this->db->escape($group) . " ");
foreach ($data as $key => $value) {
if (!is_array($value)) {
$this->db->query("UPDATE " . $this->db->dbprefix . "setting SET website_id = '" . (int)$website_id . "',
`group` = " . $this->db->escape($group) . ",
`key` = " . $this->db->escape($key) . ",
`value` = " . $this->db->escape($value) . "
");
} else {
$this->db->query("UPDATE " . $this->db->dbprefix . "setting SET
website_id = '" . (int)$website_id . "',
`group` = " . $this->db->escape($group) . ",
`key` = " . $this->db->escape($key) . ",
`value` = " . $this->db->escape(serialize($value)) . ",
serialized = '1'
");
}
}
}
public function deleteSetting($group, $website_id = 0) {
$this->db->query("DELETE FROM " . $this->db->dbprefix . "setting WHERE
website_id = '" . (int)$website_id . "' AND
`group` = " . $this->db->escape($group) . "
");
}
public function editSettingValue($group = '', $key = '', $value = '', $website_id = 0) {
if (!is_array($value)) {
$this->db->query("UPDATE " . $this->db->dbprefix . "setting SET
`value` = ". $this->db->escape($value) ." WHERE
`group` = " . $this->db->escape($group) . " AND
`key` = ". $this->db->escape($key) ."
AND website_id = '" . (int)$website_id . "'
");
} else {
$this->db->query("UPDATE " . $this->db->dbprefix . "setting SET
`value` = ". $this->db->escape(serialize($value)) .",
serialized = '1' WHERE
`group` = " . $this->db->escape($group) ."
AND `key` = " . $this->db->escape($key) . "
AND website_id = '" . (int)$website_id . "'
");
}
}
}
答案 0 :(得分:0)
您可以将WHERE子句与UPDATE查询一起使用来更新所选行,否则所有行都会受到影响。
$this->db->query("UPDATE " . $this->db->dbprefix . "setting SET website_id = '" . (int)$website_id . "',
`group` = " . $this->db->escape($group) . ",
`key` = " . $this->db->escape($key) . ",
`value` = " . $this->db->escape($value) . "
WHERE `id`= $id ");
^ replace with your condition
同样应该在else
部分进行查询。
答案 1 :(得分:0)
您错过了查询中的 WHERE
子句。也可以使用Codeigniter's Active Record代替原始SQL查询。
$data = array(
'website_id' => $website_id,
'group' => $group,
'key' => $key,
'value' => $value
);
$this->db->where('id', $id); // `id` is just for example
$this->db->update($this->db->dbprefix . 'setting', $data);
使用Active Records的优势:
1)使用Active Record功能的一个主要好处是它允许您创建独立于数据库的应用程序,因为查询语法是由每个数据库适配器生成的。
2)它提供了更简化的界面
3)它还允许更安全的查询,因为系统会自动转义值。