How to use the where method in thinkphp

01-27-2024

In thinkphp, where method is used to filter the results of database operations, and it is one of the coherent operation methods of model classes. It can complete query operations including ordinary query, expression query, shortcut query, interval query and combination query, and the syntax is instantiated object ->where ('condition'); .

The operating environment of this paper: Windows S10 system, ThinkPHP3.2 version 3.2 and Dell G3 computer.

How to use the where method in thinkphp can be used to filter the results of database operations. That is, where clause in SQL query statement.

Today, I'm going to tell you about the most commonly used but also the most complicated where method. The where method is also one of the coherent operation methods of the model class, which is mainly used for setting query and operation conditions.

The usage of where method is the essence of ThinkPHP query language, and it is also an important part and highlight of ThinkPHP ORM. It can complete query operations including ordinary query, expression query, quick query, interval query and combination query. The parameters of the where method support strings and arrays, although objects can be used, but it is not recommended.

String condition

Use string conditions to query and operate directly, such as:

$User = M("User"); //instantiate the User object $User->where('type=1 AND status=1')->select();

The resulting SQL statement is

SELECT * FROM think_user WHERE type=1 AND status=1

If version 3.1 or above is used, when using string conditions, it is recommended to cooperate with preprocessing mechanism to ensure greater security, such as:

$Model->where("id=%d and username='%s' and xx='%f'",array($id,$username,$xx))->select();

Or use:

$Model->where("id=%d and username='%s' and xx='%f'",$id,$username,$xx)->select();

If the $id variable comes from a user submission or URL address, if the incoming non-numeric type, it will be forced to format it into a digital format and then query.

The format type of string preprocessing supports specifying numbers, strings, etc. For details, please refer to the parameter description of vsprintf method.

Array condition

The where usage of array conditions is recommended by ThinkPHP.

Ordinary query

The simplest array query method is as follows:

$User = M("User"); //instantiate the User object $map['name'] = 'thinkphp'; $map['status'] = 1; //Pass the query conditions into the query method. $User->where($map)->select();

The resulting SQL statement is

SELECT * FROM think_user WHERE `name`='thinkphp' AND status=1

Recommended study: PHP video tutorial

Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us