Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class DB_Query {
- protected $table;
- protected $columns;
- protected $joins;
- protected $conditions;
- protected $order;
- protected $offset;
- protected $limit;
- protected $values;
- public function __construct($table, $columns = null) {
- $this->table = $table;
- $this->columns($columns);
- }
- public function columns($columns) {
- $this->columns = $columns;
- }
- public function where($field, $value, $op = '=') {
- $this->conditions[] = "$field $op ?";
- $this->values[] = $value;
- return $this;
- }
- public function like($field, $value) {
- return $this->where($field, "%$value%", "LIKE");
- }
- public function orderBy($order) {
- $this->order = $order;
- return $this;
- }
- public function join($table, $alias, $condition, $type = null) {
- $this->joins[] = ($type ? "$type " : "") . "JOIN $table AS $alias ON $condition";
- }
- public function limit($offset, $limit) {
- $this->offset = (int) $offset;
- $this->limit = (int) $limit;
- }
- public function page($page, $per_page) {
- $page = (int) $page;
- $per_page = (int) $per_page;
- $offset = $per_page * $page - $per_page;
- $this->limit($offset, $per_page);
- return $this;
- }
- public function execute() {
- $t = $this;
- $sql = 'SELECT ' . (is_null($t->columns) ? '*' : $t->columns) . ' FROM ' . $t->table;
- if ($t->joins) {
- $sql .= ' ' . implode(' ', $t->joins);
- }
- if ($t->conditions) {
- $sql .= ' WHERE ' . implode(' AND ', $t->conditions);
- }
- if ($t->order) {
- $sql .= " ORDER BY {$t->order}";
- }
- if ($t->limit) {
- $sql .= " LIMIT {$t->offset},{$t->limit}";
- }
- // echo $sql . '<br>';
- $stm = db::prepare($sql);
- $stm->execute($t->values);
- return $stm;
- }
- public function reset() {
- foreach (array('columns', 'joins', 'conditions', 'order', 'offset', 'limit', 'values') as $p) {
- $this->{$p} = null;
- }
- }
- public function __call($method, $args) {
- if (preg_match('/^fetch(all|column|object)?$/i', $method)) {
- $stm = $this->execute();
- $callback = array($stm, $method);
- return call_user_func_array($callback, $args);
- }
- throw new BadMethodCallException("Method $method not exists");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement