First, thinkphp insert add data

thinkphp's built-in add method is used to add data to the data table,Equivalent to insert into behavior in sql.

Adding data The add method is an implementation of create in curd (create, update, read, delete). Thinkphp supports writing data to data tables in ordinary array and object-oriented ways.

Take the example of operating the user table data in the "php mysql database tutorial" (see:Analysis of insert into data insertion usage of php + mysql) As an example to demonstrate how to add data to the data table in thinkphp.


In the indexaction controller (lib/action/indexaction.class.php), add the insert () operation:

public function insert ()
header ("content-type:text/html;charset=utf-8");
 $dao=m ("user");//instantiate the model class //build the written data array
 $data ["username"]="Little King";
 $data ["password"]=md5 ("123456");
 $data ["email"][email protected];
$data ["regdate"]=time ();//write data
if ($lastinsid=$dao->add ($data))
echo "Insert data id:$lastinsid";
else {
 $this->error ("Data writing error!");

Visit to do this:

Grammatical interpretation

m ("user") is used to efficiently instantiate a data model (m is short for new model, called shortcut method), and the parameter is the name of the table to be operated.

Next you build an array $data to hold the data.

Finally, the data is written to the library table using the add () method.Since the m shortcut method is used,You need to pass the $data array to the add () method.

add () method if the data record is successfully added,The new data record primary key is returned,Available directly.

This example actually runs sql:

insert into user
(username, password, email, regdate)
("Little King", "e10adc3949ba59abbe56e057f20f883e", "[email protected]", 1283612673)

Hint:run the example,Please confirm that the relevant account and password information of the database is correctly configured in the configuration file.See specificallyMethod for combining thinkphp public configuration file with configuration file in respective project》

Data by object

The way above is to construct an array of data,The data is then passed to the add method as a parameter and written to the data table.thinkphp also supports writing data to data tables as objects,Change the above code to:

public function insert ()
header ("content-type:text/html;charset=utf-8");
 $dao=m ("user");//instantiate the model class //assign data objects
$dao->username="Little King";
 $dao->password=md5 ("123456");
 $dao->[email protected];
 $dao->regdate=time ();//write data
if ($lastinsid=$dao->add ()) {echo "Insert data id:$lastinsid";
 else {
$this->error ("Data writing error!");

In addition to the value of the data object as a data object,There is no need to pass parameters when calling the add method to write data.

Second, thinkphp update data save method

save ()

thinkphp uses the save () method to update the database,It also supports the use of coherent operations.


public function update () {
header ("content-type:text/html;charset=utf-8");
$dao=m ("user");//data to be updated
 $data ["email"]="[email protected]";
//updated condition $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 in the above example is:

update user set email="[email protected]" where username="jack"


In order to ensure the security of the database,Avoid errors updating the entire data table,Without any update conditions,If the data object itself does not contain a primary key field,The save method does not update any database records.

So to update the data using the save () method,You must specify an update condition or the updated data contains a primary key field.

Example using primary key:

public function update () {
 header ("content-type:text/html;charset=utf-8");
 $dao=m ("user");//data 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 to be updated contains a primary key,Then thinkphp will automatically update the value of the primary key as a condition.

The above example has the same effect as the following:

//data to be updated $data ["email"]="[email protected]";

//updated condition $condition ["uid"]=2;$result=$dao->where ($condition)->save ($data);

If it ’s form data,You can also use the create () method to create a data object to update the data:

public function update () {
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,Can be handled as an object in the action class or within the model,For details, please refer to "thinkphp form data smart write create method".

Note:Create data objects with the create () method to update the data,The form must include a hidden field with a primary key name.To complete the save operation.

Third, thinkphp query data select (findall) method

thinkphp query data mainly provides the following types of queries:

select:ordinary query,Same as findall () method

find:Get a record that meets the query conditions

getby dynamic query:get a record that meets the query conditions based on a field

getfield:get the value of a field or an indexed array of multiple fields

Interval query:Get interval records that meet the query conditions

Statistical query:Obtain statistical data that meets the query conditions

Positioning query:Get one or more records that meet the query conditions

Native SQL query:supports querying or performing operations with native SQL

select ()

select () is the most common general query method in thinkphp,The result is a two-dimensional array.findall () is an alias for the select () method,It is recommended to use select ().

Read operation

The following example reads all data from the user table and displays it:

public function read ()
$dao=m ("user");//query data
$list=$dao->select ();
//dump ($list);
//Use dump () to see if the data has been read during debugging
//template variable assignment $this->assign ("list", $list);
//Output template $this->display ();

Assuming the class file corresponding to the above example is lib/action/indexaction.class.php, the corresponding template file is tpl/default/index/read.html.

Data display template

The template file is used to display the data of the user table just read.During the learning phase,Do i want to use a template,You can also use the foreach syntax directly to display the read data within a read () operation.Here is the corresponding code snippet from the template,We display the read data in a table:

<table border="1">
<th width="10%">id</th>
 <th width="30%">username</th>
 <th width="30%">Email</th>
<th>Registration time</th>
<volist name="list">
<td align="center">{$vo ["uid"]}</td>
 <td>{$vo ["username"]}</td>
<td>{$vo ["email"]}</td>
 <td>{$vo ["regdate"] | date="y-m-d h:i", ###}</td>

To learn more about thinkphp templates,See:thinkphp template.

field () Query the specified field

The select () method queries the data of all fields by default.If i want to query a field or fields,You need to use the filed () method.

filed () is a method that belongs to the coherent operation of thinkphp,As in the example above,Look up only usernames and email addresses,The query method is changed to:

$list=$dao->field ("username, email")->select ();

Use query criteria

Using thinkphp coherent operation can be very convenient to use query conditions for data query.Here are some examples of simple query conditions.

where () condition

... //Construct query conditions $condition ["username"]="admin";//Query data $list=$dao-&where;where ($condition)->select ();......

The above query is the data of the username="admin" condition.More details about thinkphp where conditions,See thinkphp where conditions.

order by

Use order by in the query to sort the data:

... //Query data $list=$dao->order ("uid desc")->select ();......

This example is the data query by order by uid desc,The meaning of the parameters in the order () method is exactly the same as the meaning in the sql statement.


Use limit in a query to limit the number of records returned by the data:

... //query data $list=$dao->limit ("4,5")->select ();......

This example is fetching records 5-10,The meaning of the parameters in the limit () method is exactly the same as the limit in the sql statement.

Coherent operation

thinkphp allows the various methods in the data object to be written together.Such as:

$list=$dao->order ("uid desc")->limit ("4,5")->select ();

This is coherent operation,For a more detailed introduction to coherent operations,See "thinkphp coherent operation".

Fourth, thinkphp delete data records delete method

thinkphp uses delete () method to delete data records in the database,It also supports the use of coherent operations.The delete () method returns the number of records affected (deleted) by the successful operation.


public function del () {
 header ("content-type:text/html;charset=utf-8");
$dao=m ("user");//delete data record with uid=5
 $result=$dao->where ("uid=5")->delete ();
 if ($result! == false) {
echo "Delete", $result, "data.";
} else {
 echo "Failed to delete data!";

The sql executed in the above example is:

delete from user where uid=5

The delete () method can be used to delete single or multiple data,Mainly depends on where () delete conditions.In addition, other methods in sequential operations such as order (), limit (), etc. can be used to construct more suitable deletion conditions:

$dao=m ("user");
$result=$dao->where ("status=0")->order ("regdate asc")->limit ("5")->delete ();

The above example is arranged in descending order according to the user registration time.Delete 5 user records with status=0.

  • Previous Analysis of Insert Into Data Insertion in PHP + MySQL
  • Next linux shell view current external network IP