A dead simple PHP 5 OO interface for building SQL queries. No manual string concatenation necessary.
Developed by Justin Stayton while at Monk Development.
- PHP 5.1.0 or newer.
To start, make sure to add the class to your autoloader or require it directly:
require "QueryBuilder.php";
Composing a query with QueryBuilder is very similar to writing the SQL by hand, as many of the directives map directly to methods:
$QueryBuilder = new QueryBuilder();
$QueryBuilder->select('*')
->from('shows')
->innerJoin('episodes', 'show_id')
->where('shows.network_id', $networkId)
->orderBy('episodes.aired_on', QueryBuilder::ORDER_BY_DESC)
->limit(20);
Now that the query is built,
$QueryBuilder->getQueryString();
returns the full SQL query string with placeholders (?), and
$QueryBuilder->getPlaceholderValues();
returns the array of placeholder values that can then be passed to your database connection or abstraction layer of choice. Or, if you'd prefer it all at once, you can get the query string with values already safely quoted:
$QueryBuilder->getQueryString(false);
If you're using PDO, however, QueryBuilder makes executing the query even easier:
$PDOStatement = $QueryBuilder->query();
QueryBuilder works directly with your PDO connection, which can be passed during creation of the QueryBuilder object
$QueryBuilder = new QueryBuilder($PDO);
or after
$QueryBuilder->setPdoConnection($PDO);
- from
- innerJoin
- leftJoin
- rightJoin
- join
- getFrom
- getFromAlias
- getFromString
- getJoinString
- mergeJoinInto
- where
- andWhere
- orWhere
- whereIn
- whereNotIn
- whereBetween
- whereNotBetween
- openWhere
- closeWhere
- getWherePlaceholderValues
- getWhereString
- mergeWhereInto
- having
- andHaving
- orHaving
- havingIn
- havingNotIn
- havingBetween
- havingNotBetween
- openHaving
- closeHaving
- getHavingPlaceholderValues
- getHavingString
- mergeHavingInto
Please open an issue to request a feature or submit a bug report. Or even if you just want to provide some feedback, I'd love to hear. I'm also available on Twitter as @jstayton.