PHP foreach 抽风了?
兄弟们,我现在正在更新一个表单里的一列数据。我选择了200行,然后用foreach逐个循环。但是发现不但更新了我选择的200行,连其余的3000行都更新了。希望帮忙看下!
$this->db->where('weekday', 5);
$this->db->where('source', 'site');
$record = $this->db->get('user', 200);
print_r($record->num_rows());
foreach ($record->result() as $row) :
$data = array(
'weekday' => 1,
);
$this->db->where('user_id', $row->user_id);
$this->db->update('user', $data);
endforeach;
提取的$record数量已通过print_r验证确实为200个。
谢谢!
更新:
在endforeach之后加上$this->db->last_query();试过了。返回结果是:UPDATE user SET weekday = 1。貌似没有包括和$record相关的条件。哪里出了问题呢?
更新:
以下兄弟们提供的回答多次试过都不行。大家可不可以帮忙想下有什么不用foreach的其他方法?
2bboy
11 years, 1 month ago
Answers
Problem solved. You cannot limit what the update function does. It will do the update for all rows in the table despite the foreach function. In order to accomplish the same objective, I've resorted to:
$update = "UPDATE user SET weekday = 2 WHERE user_category=4 LIMIT 200";
$this->db->query($update);
$update = "UPDATE user SET weekday = 2 WHERE user_category=4 LIMIT 200";
$this->db->query($update);
$update = "UPDATE user SET weekday = 2 WHERE user_category=4 LIMIT 200";
$this->db->query($update);
$update = "UPDATE user SET weekday = 2 WHERE user_category=4 LIMIT 200";
$this->db->query($update);
...... all the way to the end. Of course I used a while loop to do the above.
罗拉·罗拉
answered 11 years, 1 month ago