1. Use the where method to add query conditions
In ThinkPHP, query conditions can be added using the where method. The where method has two parameters: the first parameter is the query condition, and the second parameter is the binding parameter of the query condition. To query the records with id 1 or 2, we can use the following code:
$map['id'] = array('eq',1); $map['id'] = array('eq',2); $data = M('table_name')->where($map)->select();
We first defined the query conditions separately, one with id 1 and the other with id 2, and then added them to $ in the map array. We then pass this array to the query operation using the where method. The query results will return an array of records that meet the conditions.
2. Use array method to pass query conditions
In addition to using the where method, we can also use array method to pass query conditions. Using this method, we only need to add query conditions to the $map array. We can use the following code to query which records in the table have id equal to 1 or equal to 2
$map['id'] = array('in', '1,2'); $data = M('table_name')->where($map)->select();
We have defined the query conditions in the code, which is limited to the id in the $map array being 1 or 2. We used the "in" operator to uniformly retrieve records with id 1 or 2. In this way, we can easily set "or" query conditions.
3. Use string splicing
Sometimes, we can use string splicing to implement "or" query conditions. For example, if we want to retrieve records that satisfy both condition A and condition B, we can use the following code:
$map['字段名'] = array('exp', '(条件A) OR (条件B)'); $data = M('table_name')->where($map)->select();
In the above code, we use the exp operator to pass a string containing two conditions SQL statement. Note that this condition needs to be enclosed in parentheses to ensure correct logic.
The above is the detailed content of How to perform conditional query in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!