thinkphp Save () method
The Save () method is used in thinkphp to update the database and also supports the use of coherent operations.
Example:
Public functionUpdate () {Header("content-type:text/html; Charset=utf-8 "); $Dao= M ("User"); //data that needs to be updated $data[' email '] = ' [email protected] '; //Conditions for Updates $condition[' username '] = ' Jack '; $result=$Dao->where ($condition)->save ($data); //or: $resul t= $Dao->where ($condition)->data ($data)->save (); if($result!==false){ Echo' Data updated successfully! ‘; }Else{ Echo' Data update failed! ‘; }}
The SQL statement executed by the example above is:
UPDATE user SET email= ' [email protected] ' WHERE username= ' Jack '
Tips
In order to ensure the security of the database, to avoid errors update the entire data table, if there is no update condition, the data object itself does not contain the primary key field, the Save method does not update the records of any database.
Therefore, to update the data using the Save () method, you must specify an update condition or include the primary key field in the updated data .
Examples of using primary keys:
Public functionUpdate () {Header("content-type:text/html; Charset=utf-8 "); $Dao= M ("User"); //data that needs to be updated $data[' email '] = ' [email protected] '; $data[' uid '] = 2; $result=$Dao->save ($data); if($result!==false){ Echo' Data updated successfully! ‘; }Else{ Echo' Data update failed! ‘; }}
If the data that needs to be updated contains the primary key, then thinkphp automatically updates the value of the primary key as a condition. The above example has the same effect as the following:
// Data that needs to be updated $data [' email '] = ' [email protected] '; // conditions for updates $condition [' uid '] = 2; $result $Dao->where ($condition)->save ($data);
If it is form data, you can also use the Create () method to make data objects to update the data:
Public functionUpdate () {Header("content-type:text/html; Charset=utf-8 "); $Dao= D ("User"); if($vo=$Dao-Create ()) { $result=$Dao-Save (); if($result!==false){ Echo' Data updated successfully! ‘; }Else{ Echo' Data update failed! ‘; } }Else{ $this->error ($Form-GetError ()); }}
If the updated data needs to be processed logically, it can be handled in the object or within the model, and the thinkphp form data is intelligently written to the Create method.
Note: To update data by creating a data object with the Create () method, the form must contain a hidden field with a primary key name in order to complete the save operation.
Data unchanged, commit update, return false;
Data change, commit update, return true;
The return is not false but 0 you want to use identity to determine if commit failed
Original link
thinkphp Update Data Save method