当我更新我的数据库行时。由于某种原因,它将所有值更新为与上次输入相同,这非常奇怪。
如何让它工作,以便所有行都不会更新所有相同的值?
这就是我的数据库的工作方式。 $ group =' config'。 $ key = example:' config_name'。 $ value =输入$ key的内容。
在我的模型中,我使用foreach ($data as $key => $value) {
使用最后一个输入值更新所有值是非常奇怪的。
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_website_setting extends CI_Model {
public function editWebsite($group , $data, $website_id = 0) {
foreach ($data as $key => $value) {
// Make sure only keys belonging to this group are used
if (substr($key, 0, strlen($group)) == $group) {
if (!is_array($value)) {
$this->db->set('group', $group);
$this->db->set('value', $key);
$this->db->set('value', $value);
$this->db->set('website_id', $website_id);
$this->db->update($this->db->dbprefix . 'setting');
} else {
$this->db->set('group', $group);
$this->db->set('value', $key);
$this->db->set('value', $value);
$this->db->set('website_id', $website_id);
$this->db->update($this->db->dbprefix . 'setting');
}
}
}
}
}
控制器
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Website_settings extends Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/setting/setting', 'english');
}
public function index() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['entry_name'] = $this->lang->line('entry_name');
$data['entry_owner'] = $this->lang->line('entry_owner');
if (!empty($this->input->post('config_name'))) {
$data['config_name'] = $this->input->post('config_name');
} else {
$data['config_name'] = $this->settings->get('config_name');
}
if (!empty($this->input->post('config_owner'))) {
$data['config_owner'] = $this->input->post('config_owner');
} else {
$data['config_owner'] = $this->settings->get('config_owner');
}
$this->load->library('form_validation');
$this->form_validation->set_rules('config_name', 'Website Name');
$this->form_validation->set_rules('config_owner', 'Your Name');
if ($this->form_validation->run() == FALSE) {
return $this->load->view('setting/website_settings', $data);
} else {
$this->load->model('admin/setting/model_website_setting');
$this->model_website_setting->editWebsite('config', $this->input->post());
$this->session->set_flashdata('success', 'You have updated settings!');
redirect('admin/setting/website');
}
}
}
答案 0 :(得分:0)
如果我是你,我会使用内置的update_batch
,并且不会在每个循环上放置update
。
foreach ($data as $key => $value) {
// Make sure only keys belonging to this group are used
if (substr($key, 0, strlen($group)) == $group) {
if (!is_array($value)) {
// this is where you do the logic
// if the value is the same do not insert in the update array
// if the value is not the same then insert it on the update array
$update[] = array(
'group' => $group,
'value' => $key,
'website_id' => $website_id
);
} else {
$update[] = array(
'group' => $group,
'value' => $key,
'website_id' => $website_id
);
}
}
}
$this->db->update_batch($this->db->dbprefix . 'setting', $update , 'website_id');
如何在未经测试的代码上使用更新批处理的示例。