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;
}
}