Home Backend Development PHP Tutorial Detailed explanation of where() usage in ThinkPHP_php example

Detailed explanation of where() usage in ThinkPHP_php example

May 16, 2016 pm 07:54 PM

This article introduces the usage of ThinkPHP’s where() method. The where method can be used to filter the results of database operations. That is, the where clause in the SQL query statement.

Today I will tell you about the where method, which is the most commonly used but also the most complex query. The where method is also one of the coherent operation methods of the model class and is mainly used for query and operation condition setting.

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

String condition

Use string conditions to directly query and operate, for example:

$User = M("User"); // 实例化User对象
$User->where('type=1 AND status=1')->select(); 
Copy after login

The final generated SQL statement is

SELECT * FROM think_user WHERE type=1 AND status=1
Copy after login

If you use version 3.1 or above, when using string conditions, it is recommended to cooperate with the preprocessing mechanism to ensure more security, for example:

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

Or use:

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

If the $id variable comes from user submission or URL address, if the input is a non-numeric type, it will be forced to be formatted into a numeric format before querying.
The string preprocessing format type supports specifying numbers, strings, etc. For details, please refer to the parameter description of the vsprintf method.

Array condition

The where usage of array conditions is the usage recommended by ThinkPHP.

General query

The simplest array query method is as follows:

$User = M("User"); // 实例化User对象
$map['name'] = 'thinkphp';
$map['status'] = 1;
// 把查询条件传入查询方法
$User->where($map)->select(); 
Copy after login

The final generated SQL statement is

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

Expression query

The above query condition is just a simple equality judgment. You can use query expressions to support more SQL query syntax. The usage format of query expressions:

$map['字段1'] = array('表达式','查询条件1');
$map['字段2'] = array('表达式','查询条件2');
$Model->where($map)->select(); // 也支持
Copy after login

Expressions are not case-sensitive. The supported query expressions are as follows, and their respective meanings are:

Expression Meaning

EQ equals (=)
NEQ is not equal to (<>)
GT is greater than (>)
EGT greater than or equal to (>=)
LT is less than (<)
ELT Less than or equal to (<=)
LIKE fuzzy query
[NOT] BETWEEN (not in) interval query
[NOT] IN IN query
EXP expression query, supports SQL syntax

An example is as follows:

EQ: Equal (=)

For example:

$map['id'] = array('eq',100);
Copy after login

is equivalent to the following query

$map['id'] = 100;
Copy after login
The query condition represented by

is id = 100

NEQ: Not equal to (<>)

For example:

$map['id'] = array('neq',100);
Copy after login
The query condition represented by

is id <> 100

GT: greater than (>)

For example:

$map['id'] = array('gt',100);
Copy after login
The query condition represented by

is id > 100

EGT: greater than or equal to (>=)

For example:

$map['id'] = array('egt',100);
Copy after login
The query condition represented by

is id >= 100

LT: less than (<)

For example:

$map['id'] = array('lt',100);
Copy after login
The query condition represented by

is id < 100

ELT: Less than or equal to (<=)

For example:

$map['id'] = array('elt',100);
Copy after login
The query condition represented by

is id <= 100

[NOT] LIKE: Same as sql LIKE

For example:

$map['name'] = array('like','thinkphp%');
Copy after login

The query condition becomes name like 'thinkphp%'

If the DB_LIKE_FIELDS parameter is configured, some fields will also automatically perform fuzzy queries. For example, set:

'DB_LIKE_FIELDS'=>'title|content'
Copy after login
If

, use

$map['title'] = 'thinkphp';
Copy after login

The query condition will become name like '%thinkphp%'
Support array mode, such as

$map['a'] =array('like',array('%thinkphp%','%tp'),'OR');
$map['b'] =array('notlike',array('%thinkphp%','%tp'),'AND');
Copy after login
The query condition generated by

is:

(a like '%thinkphp%' OR a like '%tp') AND (b not like '%thinkphp%' AND b not like '%tp')
Copy after login

[NOT] BETWEEN: Same as SQL's [not] between, query conditions support strings or arrays, for example:

$map['id'] = array('between','1,8');
Copy after login

is equivalent to:

$map['id'] = array('between',array('1','8'));
Copy after login

The query condition becomes id BETWEEN 1 AND 8

[NOT] IN: Same as SQL's [not] in, query conditions support strings or arrays, for example:

$map['id'] = array('not in','1,5,8');
Copy after login

is equivalent to:

$map['id'] = array('not in',array('1','5','8'));
Copy after login

The query condition becomes id NOT IN (1,5, 8)

EXP: Expression, supports more complex query situations

For example:

$map['id'] = array('in','1,3,8');
Copy after login

can be changed to:

$map['id'] = array('exp',' IN (1,3,8) ');
Copy after login

exp查询的条件不会被当成字符串,所以后面的查询条件可以使用任何SQL支持的语法,包括使用函数和字段名称。

查询表达式不仅可用于查询条件,也可以用于数据更新,例如:

$User = M("User"); // 实例化User对象
// 要修改的数据对象属性赋值
$data['name'] = 'ThinkPHP';
$data['score'] = array('exp','score+1');// 用户的积分加1
$User->where('id=5')->save($data); // 根据条件保存修改的数据
Copy after login

快捷查询

where方法支持快捷查询方式,可以进一步简化查询条件的写法,例如:

一、实现不同字段相同的查询条件

$User = M("User"); // 实例化User对象
$map['name|title'] = 'thinkphp';
// 把查询条件传入查询方法
$User->where($map)->select(); 
Copy after login

查询条件就变成 name= 'thinkphp' OR title = 'thinkphp'

二、实现不同字段不同的查询条件

$User = M("User"); // 实例化User对象
$map['status&title'] =array('1','thinkphp','_multi'=>true);
// 把查询条件传入查询方法
$User->where($map)->select(); 
Copy after login

'_multi'=>true必须加在数组的最后,表示当前是多条件匹配,这样查询条件就变成 status= 1 AND title = 'thinkphp' ,查询字段支持更多的,例如:

$map['status&score&title'] =array('1',array('gt','0'),'thinkphp','_multi'=>true);
Copy after login

查询条件就变成 status= 1 AND score >0 AND title = 'thinkphp'

注意:快捷查询方式中“|”和“&”不能同时使用。

区间查询

where方法支持对某个字段的区间查询,例如:

$map['id'] = array(array('gt',1),array('lt',10)) ;

得到的查询条件是: (`id` > 1) AND (`id` < 10)

$map['id'] = array(array('gt',3),array('lt',10), 'or') ;

得到的查询条件是: (`id` > 3) OR (`id` < 10)

$map['id'] = array(array('neq',6),array('gt',3),'and');

得到的查询条件是:(`id` != 6) AND (`id` > 3)
最后一个可以是AND、 OR或者 XOR运算符,如果不写,默认是AND运算。

区间查询的条件可以支持普通查询的所有表达式,也就是说类似LIKE、GT和EXP这样的表达式都可以支持。另外区间查询还可以支持更多的条件,只要是针对一个字段的条件都可以写到一起,例如:

$map['name'] = array(array('like','%a%'), array('like','%b%'), array('like','%c%'), 'ThinkPHP','or'); 
Copy after login

最后的查询条件是:

(`name` LIKE '%a%') OR (`name` LIKE '%b%') OR (`name` LIKE '%c%') OR (`name` = 'ThinkPHP')
Copy after login

组合查询

组合查询用于复杂的查询条件,如果你需要在查询的时候同时偶尔使用字符串却又不希望丢失数组方式的灵活的话,可以考虑使用组合查询。

组合查询的主体还是采用数组方式查询,只是加入了一些特殊的查询支持,包括字符串模式查询(_string)、复合查询(_complex)、请求字符串查询(_query),混合查询中的特殊查询每次查询只能定义一个,由于采用数组的索引方式,索引相同的特殊查询会被覆盖。

一、字符串模式查询(采用_string 作为查询条件)

数组条件还可以和字符串条件混合使用,例如:

$User = M("User"); // 实例化User对象
$map['id'] = array('neq',1);
$map['name'] = 'ok';
$map['_string'] = 'status=1 AND score>10';
$User->where($map)->select(); 
Copy after login

最后得到的查询条件就成了:

( `id` != 1 ) AND ( `name` = 'ok' ) AND ( status=1 AND score>10 )
Copy after login

二、请求字符串查询方式

请求字符串查询是一种类似于URL传参的方式,可以支持简单的条件相等判断。

$map['id'] = array('gt','100');
$map['_query'] = 'status=1&score=100&_logic=or';
Copy after login

得到的查询条件是:`id`>100 AND (`status` = '1' OR `score` = '100')

三、复合查询

复合查询相当于封装了一个新的查询条件,然后并入原来的查询条件之中,所以可以完成比较复杂的查询条件组装。
例如:

$where['name'] = array('like', '%thinkphp%');
$where['title'] = array('like','%thinkphp%');
$where['_logic'] = 'or';
$map['_complex'] = $where;
$map['id'] = array('gt',1);
Copy after login

查询条件是

( id > 1) AND ( ( name like '%thinkphp%') OR ( title like '%thinkphp%') )
Copy after login

复合查询使用了_complex作为子查询条件来定义,配合之前的查询方式,可以非常灵活的制定更加复杂的查询条件。

很多查询方式可以相互转换,例如上面的查询条件可以改成:

$where['id'] = array('gt',1);
$where['_string'] = ' (name like "%thinkphp%") OR ( title like "%thinkphp") ';
Copy after login

最后生成的SQL语句是一致的。

多次调用

3.1.3版本开始,where方法支持多次调用,但字符串条件只能出现一次,例如:

$map['a'] = array('gt',1);
$where['b'] = 1;
$Model->where($map)->where($where)->where('status=1')->select();
Copy after login

多次的数组条件表达式会最终合并,但字符串条件则只支持一次。

关于ThinkPHP中where()方法的使用,本文就介绍这么多,希望对您有所帮助,谢谢!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain Arrow Functions (short closures) introduced in PHP 7.4. Explain Arrow Functions (short closures) introduced in PHP 7.4. Apr 06, 2025 am 12:01 AM

The arrow function was introduced in PHP7.4 and is a simplified form of short closures. 1) They are defined using the => operator, omitting function and use keywords. 2) The arrow function automatically captures the current scope variable without the use keyword. 3) They are often used in callback functions and short calculations to improve code simplicity and readability.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

See all articles