Skip to content

Instantly share code, notes, and snippets.

@bgallagh3r
Created September 11, 2014 22:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bgallagh3r/6f005e472411be847810 to your computer and use it in GitHub Desktop.
Save bgallagh3r/6f005e472411be847810 to your computer and use it in GitHub Desktop.
A helper class to build prepared statements using WordPress's WPDB class.
<?php
/**
* A helper class to allow you to easily build prepared statements
* for use with Wordpress's WPDB class.
*
* Usage: $this->orderBy('column', 'asc')->limit(50)->getQuery();
*/
class QueryBuilder {
/**
* Table name to select rows from.
* @var string
*/
private $table;
/**
* Associative array, usually $_GET vars.
* @var array
*/
private $params;
/**
* A string for a SQL LIMIT
* @var mixed
*/
private $limit;
/**
* A string for SQL ORDER BY
* @var mixed
*/
private $orderBy;
function __construct($table, array $params)
{
$this->table = $table;
$this->params = $params;
}
/**
* Returns the prepared statement.
* @return string
*/
public function getQuery()
{
return $this->buildQuery();
}
/**
* Build a prepared SQL statement using WordPress's WPDB class.
*
* @return string
*/
private function buildQuery()
{
global $wpdb;
foreach ($this->params as $key => $value) {
$format = is_numeric($value) ? '%d' : '%s';
$sql[] = " `$key` = $format";
$values[] = $value;
}
return $wpdb->prepare(
"SELECT * FROM `{$this->table}` ".
"WHERE " . implode(' AND ', $sql).
$this->limit .
$this->orderBy
, $values);
}
/**
* Set a SQL LIMIT on the query string.
*
* @param $limit
* @return QueryBuilder
*/
public function limit($limit)
{
$this->limit = ' LIMIT '. intval($limit);
return $this;
}
/**
* Set column to order results by
*
* @param string $orderBy DB Column
* @param string $order Sort Order
* @return $this
*/
public function orderBy($orderBy, $order = 'ASC')
{
$this->orderBy = ' ORDER BY `'. $orderBy .'` '.$order;
return $this;
}
}
@bgallagh3r
Copy link
Author

I built this for a small plugin I wrote that had a bunch of selects that allowed users to filter data using $_GET variables. I didn't want to do a bunch of if / else statements so I wrote this class so I could do something like

$builder = new QueryBuilder($table, $_GET)
$query = $builder->getQuery();

without the need to use a bunch of $wpdb->prepare() statements you can now use this class with any FLAT associative array.

I expect to modify this in the future but for now I figured it fit my needs for the time being.

@brucevdkooij
Copy link

@bgallagh3r I stumbled on this through some Googling and just wanted to point out that I think this is susceptible to SQL injection if you use it as described (passing $_GET) because the keys are not escaped.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment