有時候須要批量修改數據,若是循環修改單個,則會很是影響數據庫鏈接量,比較好的方式就是拼接成一條sql,一次執行
php
/** * 批量更新 * @param [arr] $datas [要保存的數據集] * $data[] = array('id'=>1,'value'=>value1); $data[] = array('id'=>2,'value'=>value2); $data[] = array('id'=>3,'value'=>value3); * @param [string] $database_table_name [數據庫表名] * @param [string] $primary_key [主鍵名] * @return [int] [成功修改的條數] */ function dbSaveAll($datas, $database_table_name, $primary_key){ $sql = ''; //Sql $lists = []; //記錄集$lists $pk = $primary_key;//獲取主鍵 foreach ($datas as $data) { foreach ($data as $key=>$value) { if($pk===$key){ $ids[]=$value; }else{ $lists[$key].= sprintf("WHEN %u THEN '%s' ",$data[$pk],$value); } } } foreach ($lists as $key => $value) { $sql.= sprintf("`%s` = CASE `%s` %s END,",$key,$pk,$value); } $sql = sprintf('UPDATE __%s__ SET %s WHERE %s IN ( %s )',strtoupper($database_table_name),rtrim($sql,','),$pk,implode(',',$ids)); return M()->execute($sql); }調用
// 保存到數據庫 $result = dbSaveAll($vote_projects, 'Vote_project', 'order_number'); if($result){ $this->success('寫入成功!', __APP__ . '/Admin/Vote/get_all_pro'); } else { $this->error('數據已同步,無需重複寫入'); }