Advertisement
Guest User

Untitled

a guest
Jul 29th, 2015
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * A helper class to allow you to easily build prepared statements
  5. * for use with Wordpress's WPDB class.
  6. *
  7. * Usage: $this->orderBy('column', 'asc')->limit(50)->getQuery();
  8. */
  9. class QueryBuilder {
  10.  
  11. /**
  12. * Table name to select rows from.
  13. * @var string
  14. */
  15. private $table;
  16.  
  17. /**
  18. * Associative array, usually $_GET vars.
  19. * @var array
  20. */
  21. private $params;
  22.  
  23. /**
  24. * A string for a SQL LIMIT
  25. * @var mixed
  26. */
  27. private $limit;
  28.  
  29. /**
  30. * A string for SQL ORDER BY
  31. * @var mixed
  32. */
  33. private $orderBy;
  34.  
  35.  
  36. function __construct($table, array $params)
  37. {
  38. $this->table = $table;
  39. $this->params = $params;
  40. }
  41.  
  42. /**
  43. * Returns the prepared statement.
  44. * @return string
  45. */
  46. public function getQuery()
  47. {
  48. return $this->buildQuery();
  49. }
  50.  
  51. /**
  52. * Build a prepared SQL statement using WordPress's WPDB class.
  53. *
  54. * @return string
  55. */
  56. private function buildQuery()
  57. {
  58. global $wpdb;
  59.  
  60. foreach ($this->params as $key => $value) {
  61. $format = is_numeric($value) ? '%d' : '%s';
  62. $sql[] = " `$key` = $format";
  63. $values[] = $value;
  64. }
  65.  
  66. return $wpdb->prepare(
  67. "SELECT * FROM `{$this->table}` ".
  68. "WHERE " . implode(' AND ', $sql).
  69. $this->limit .
  70. $this->orderBy
  71. , $values);
  72. }
  73.  
  74. /**
  75. * Set a SQL LIMIT on the query string.
  76. *
  77. * @param $limit
  78. * @return QueryBuilder
  79. */
  80. public function limit($limit)
  81. {
  82. $this->limit = ' LIMIT '. intval($limit);
  83. return $this;
  84. }
  85.  
  86. /**
  87. * Set column to order results by
  88. *
  89. * @param string $orderBy DB Column
  90. * @param string $order Sort Order
  91. * @return $this
  92. */
  93. public function orderBy($orderBy, $order = 'ASC')
  94. {
  95. $this->orderBy = ' ORDER BY `'. $orderBy .'` '.$order;
  96. return $this;
  97. }
  98.  
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement