Native queries (query builder 13)
The Db class supports native SQL query operations, mainly including the following two methods:
query method
query method is used to execute SQL Query operation returns the query result data set (array) just like the select method.
Usage example:
Db::query("select * from think_user where status=1");
If you currently use a distributed database and set up read-write separation, the query method will be executed on the read server by default, regardless of what your SQL statement is.
If you want to read from the main library, you can use
Db::master(true)->query("select * from think_user where status=1");
The chain operation methods supported by the new version of query method include:
Chain method | Description |
---|---|
cache | Query cache |
master | Whether the main database query (distributed valid) |
procedure | Stored procedure query |
execute method
execute is used for sql operations of updating and writing data. If the data is illegal or the query is wrong, false is returned, otherwise the number of records affected is returned.
Usage example:
Db::execute("update think_user set name='thinkphp' where status=1");
Parameter binding
Supports parameter binding during native query, including question mark placeholder or named account character, for example:
Db::query("select * from think_user where id=? AND status=?", [8, 1]); // 命名绑定 Db::execute("update think_user set name=:name where status=:status", ['name' => 'thinkphp', 'status' => 1]);
Note that parameter binding is not supported for table names