SoFunction
Updated on 2025-04-04

A brief analysis of the difference between execute and query methods in ThinkPHP

When I was first learning ThinkPHP, many people were confused about the difference between execute() and query() methods. This article briefly analyzes the difference between the two.
As we all know, both execute() and query() methods in ThinkPHP can directly enter SQL statements in parameters. But the difference isexecute() is usually used to execute SQL statements such as insert or update.,andQuery is often used to execute select and other statements
The execute() method will return the number of records affected, If SQL select statement is executed, the returned result will be the total number of records in the table:
Copy the codeThe code is as follows:
$model = M( "MyTable" );
$result = $model ->execute( 'update MyTable set name=aaa where id=11'); //The total number of rows will be returned

The query() method will return the dataset
Copy the codeThe code is as follows:
$model = M( "MyTable" );
$result = $model ->query( 'select * from  MyTable' ); // Will return array()