Created
September 11, 2014 22:30
-
-
Save bgallagh3r/6f005e472411be847810 to your computer and use it in GitHub Desktop.
A helper class to build prepared statements using WordPress's WPDB class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.