This is a helper class for building the WHERE part of an SQL string out of pieces. It has methods add
, addClause
, negateLast
, and negate
, which are all demonstrated in the example below.
Once you've built your WhereClause, it can be injected into a query with the %? or %l parameters.
$where = new WhereClause('and'); // create a WHERE statement of pieces joined by ANDs
$where->add('username=%s', 'Joe');
$where->add('password=%s', 'mypass');
// SELECT * FROM accounts WHERE (`username`='Joe') AND (`password`='mypass')
$results = DB::query("SELECT * FROM accounts WHERE %?", $where);
// DELETE FROM accounts WHERE (`username`='Joe') AND (`password`='mypass')
DB::delete('accounts', '%?', $where);
// UPDATE accounts SET is_admin=1 WHERE (`username`='Joe') AND (`password`='mypass')
DB::update('accounts', array('is_admin' => 1), '%?', $where);
$subclause = $where->addClause('or'); // add a sub-clause with ORs
$subclause->add('age=%i', 15);
$subclause->add('age=%i', 18);
$subclause->negateLast(); // negate the last thing added (age=18)
// SELECT * FROM accounts WHERE (`username`='Joe') AND (`password`='mypass') AND ((`age`=15) OR (NOT(`age`=18)))
$results = DB::query("SELECT * FROM accounts WHERE %?", $where);
$subclause->negate(); // negate this entire subclause
// SELECT * FROM accounts WHERE (`username`='Joe') AND (`password`='mypass') AND (NOT((`age`=15) OR (NOT(`age`=18))))
$results = DB::query("SELECT * FROM accounts WHERE %?", $where);