Thinkphp method for batch data update

Source: Internet
Author: User
This article mainly introduces the summary of Thinkphp data batch update methods, which is very good and has reference value, for more information about how to update data in batches using thinkphp, see the following small series!

Method 1:

// Batch modify the field keyword field of the data two-dimensional array. for details, refer to the ci batch modify function parameter passing mode function batch_update ($ table_name = '', $ data = array (), $ field = '') {if (! $ Table_name |! $ Data |! $ Field) {return false;} else {$ SQL = 'update '. $ table_name;} $ con = array (); $ con_ SQL = array (); $ fields = array (); foreach ($ data as $ key => $ value) {$ x = 0; foreach ($ value as $ k => $ v) {if ($ k! = $ Field &&! $ Con [$ x] & $ x = 0) {$ con [$ x] = "set {$ k} = (CASE {$ field }";} elseif ($ k! = $ Field &&! $ Con [$ x] & amp; $ x> 0) {$ con [$ x] = "{$ k} = (CASE {$ field }";} if ($ k! = $ Field) {$ temp = $ value [$ field]; $ con_ SQL [$ x]. = "when' {$ temp} 'then' {$ v} '"; $ x ++ ;}}$ temp = $ value [$ field]; if (! In_array ($ temp, $ fields) {$ fields [] = $ temp; }}$ num = count ($ con)-1; foreach ($ con as $ key = >$ value) {foreach ($ con_ SQL as $ k => $ v) {if ($ k ==key key & $ key <$ num) {$ SQL. = $ value. $ v. 'End), ';} elseif ($ k ==$ key & $ key ==$ num) {$ SQL. = $ value. $ v. 'End) ';}}$ str = implode (', ', $ fields); $ SQL. = "where {$ field} in ({$ str})"; $ res = M ($ table_name)-> execute ($ SQL); return $ res ;} // test function test () {$ update_array = array (); for ($ I = 2; $ I <7; $ I ++) {$ data = array (); $ data ['id'] = $ I; $ data ['memeber _ type'] = 2; $ data ['memeber _ type_state '] = 1; $ update_array [] = $ data;} $ res = $ this-> batch_update ('yl _ member ', $ update_array, id); var_dump ($ res );}

Method 2:

It is an update record that repeats one by one. Update a record once, which has poor performance and can easily cause blocking.

Can I update an SQL statement in batches? Mysql does not provide a direct method for batch update, but it can be implemented with tips.

UPDATE categories SET display_order = CASE id WHEN 1 THEN 3 WHEN 2 THEN 4 WHEN 3 THEN 5 ENDWHERE id IN (1,2,3)

This SQL statement indicates that the display_order field is updated. if id = 1, the value of display_order is 3. if id = 2, the value of display_order is 4, if id = 3, the value of display_order is 5.
The condition statements are written together.

The where part does not affect code execution, but it increases the SQL execution efficiency. Make sure that the SQL statement only executes the number of rows to be modified. here, only three rows of data are updated, and the where clause ensures that only three rows of data are executed.

If you want to update multiple values, you only need to slightly modify them:

UPDATE categories SET display_order = CASE id WHEN 1 THEN 3 WHEN 2 THEN 4 WHEN 3 THEN 5 END, title = CASE id WHEN 1 THEN 'New Title 1'WHEN 2 THEN 'New Title 2'WHEN 3 THEN 'New Title 3'ENDWHERE id IN (1,2,3)

Practical application

$display_order = array( 1 => 4, 2 => 1, 3 => 2, 4 => 3, 5 => 9, 6 => 5, 7 => 8, 8 => 9 ); $ids = implode(',', array_keys($display_order)); $sql = "UPDATE categories SET display_order = CASE id "; foreach ($display_order as $id => $ordinal) { $sql .= sprintf("WHEN %d THEN %d ", $id, $ordinal); } $sql .= "END WHERE id IN ($ids)"; echo $sql;

Method 2 is not recommended.

Method 3:

/** @ Param $ saveWhere: array of primary key IDs to be updated * @ param $ saveData: data corresponding to the ID array to be updated * @ param $ tableName: indicates * @ param $ saveWhere: returns the primary key ID array after successful update. */public function saveAll ($ saveWhere, & $ saveData, $ tableName) {if ($ saveWhere = null | $ tableName = null) return false; // Obtain the updated primary key id $ key = array_keys ($ saveWhere) [0]; // get the length of the update list $ len = count ($ saveWhere [$ key]); $ flag = true; $ model = isset ($ model )? $ Model: M ($ tableName); // enable the transaction processing mechanism $ model-> startTrans (); // record the update failure ID $ error = []; for ($ I = 0; $ I <$ len; $ I ++) {// pre-processing SQL statement $ isRight = $ model-> where ($ key. '= '. $ saveWhere [$ key] [$ I])-> save ($ saveData [$ I]); if ($ isRight = 0) {// record failed updates: $ error [] = $ I; $ flag = false;} // $ flag = $ flag & $ isRight ;} if ($ flag) {// if both are true, submit $ model-> commit (); return $ saveWhere;} elseif (count ($ error)> 0 & count ($ error) <$ len) {// first roll back the original preprocessing $ model-> rollback (); for ($ I = 0; $ I
 
  
SaveAll ($ saveWhere, $ saveData, $ tableName); return $ saveWhere;} else {// roll back $ model-> rollback (); return false ;}}
 

Call in the test method:

Public function test () {// primary key array of the data table to be updated $ where ['id'] = array (, 80, 83 ); // the data to be updated corresponding to the ID primary key array $ save = array ('school '=> 'dk Univisity01', 'isexport' => 0 ), array ('school '=> 'dk Univisity02', 'isport' => 0), array ('school '=> 'dk univisity03', 'isport' => 0 ), array ('school '=> 'dk Univisity04', 'isport' => 0), array ('school '=> '', 'isport' => 0 ), // array ('school '=> 'univisity05', 'isport' => 0),); $ f = $ this-> saveAll ($ where, $ save, 'want'); if (count ($ f ['id'])> 0) {// returns the updated ID array echo "This is success:
"; Dump ($ f); echo 'OK';} else {// update failed operation echo" This is failed:
"; Dump ($ f); echo 'error ';}}

The above is a summary of the Thinkphp batch data update method introduced by Xiaobian. I hope it will help you. if you have any questions, please leave a message and I will reply to you in a timely manner. I would like to thank you for your support for PHP chinnet!

For more information about how to update data in batches in Thinkphp, see The PHP Chinese website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.