thinkphp Implementation of like Fuzzy Query Example

  • 2021-07-24 10:16:26
  • OfStack

This article describes the example of thinkphp implementation of like fuzzy query method, to share for your reference. The specific implementation method is as follows:

At present, more and more people use thinkphp framework to develop projects. Because of its good encapsulation, many parts of pure PHP development are not easy to get started. This paper takes like fuzzy query as an example to illustrate this.

Here, the usage is mainly illustrated by examples:

ThinkPHP can support using strings as query criteria directly, but in most cases it is recommended to use indexed arrays or objects as query criteria because it is safer.

1. Use strings as query criteria

This is the most traditional way, but the security is not high.
For example:

$User = M("User"); //  Instantiation 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 you are doing a multi-field query, the default logical relationship between the fields is logic and AND, but you can change the default logical judgment with the following rule, by defining the query logic using _ logic:

$User = M("User"); //  Instantiation User Object 
$condition['name'] = 'thinkphp';
$condition['account'] = 'thinkphp';
$condition['_logic'] = 'OR';
// Passing query criteria into query methods
$User->where($condition)->select();

The resulting SQL statement is

SELECT * FROM think_user WHERE `name`='thinkphp' OR `account`='thinkphp'

2. Array mode as query condition

Said so much like query how to achieve, see below

$userForm=M('user'); 
$where['name']=array('like','jb51%');
$userForm->where($where)->select();

The like query here is:
name like 'jb51%'

Query statement:

$where['name']=array('like',array('%jb51%','%.com'),'OR');

The like query here is:
name like '%jb51%' or name like '%.com'

Query statement:

$where['name']=array(array('like','%a%'),array('like','%b%'),array('like','%c%'),'jb51','or');

The like query here is:
(`name` LIKE '%a%') OR (`name` LIKE '%b%') OR (`name` LIKE '%c%') OR (`name` = 'jb51')

Query statement:

SELECT * FROM think_user WHERE type=1 AND status=1
0
The like query here is:
name like '%jb51%' or title like '%jb51'

Readers who are interested in thinkPHP can check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "smarty Template Introduction Basic Tutorial" and "PHP Template Technology Summary".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: