Skip to Content search facebook instagram pinterest twitter youtube

Where clause builder

Pdb::buildClause

Builds a clause string by combining conditions, e.g. for a WHERE or ON clause.

The resultant clause will contain ? markers for safe use in a prepared SQL statement.

The statement and the generated $values can then be run via Pdb::query.

Each condition (see $conditions) is one of:

  • The scalar value 1 or 0 (to match either all or no records)
  • A column => value pair
  • An array with three elements: [column, operator, value(s)].

Conditions are usually combined using AND, but can also be OR or XOR; see the $combine parameter.

$conditions = [];
$conditions[] = ['active' => 1];
$conditions[] = ['date_added', 'BETWEEN', ['2015-01-01', '2016-01-01']];

$params = [];
$where = Pdb::buildClause($conditions, $params);

// Variable contents:
// $where == "active = ? AND date_added BETWEEN ? AND ?"
// $params == [1, '2015-01-01', '2016-01-01'];

$q = "SELECT * FROM ~my_table WHERE {$where}";
$res = Pdb::query($q, $params, 'pdo');

foreach ($res as $row) {
    // Record processing here
}
$res->closeCursor();

Condition examples

['id', '=', 3]

['date_added', 'BETWEEN', ['2010', '2015']]

['status', 'IN', ['ACTIVE', 'APPROVE']]

Simple operators:

= , <= , >= , < , > , != , <>

Operators for LIKE conditions; escaping of characters like % is handled automatically:

CONTAINS string
BEGINS string
ENDS string

Other operators:

IS string 'NULL' or 'NOT NULL'
BETWEEN array of 2 values
(NOT) IN array of values
IN SET string -- note the order matches other operators; ['column', 'IN SET', 'val1,ca']