Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class db{
- static $host;
- static $user;
- static $pass;
- static $db;
- static $charset = 'UTF8';
- static $pdo;
- /**
- * Creates a PDO database object. If not arguments are passed and a connection has already been
- * established the function will do nothing.
- * @param string $host optional MySQL server address
- * @param string $user optional MySQL username
- * @param string $pass optional MySQL password
- * @param string $pass optional MySQL database name
- */
- static function connect($host = null, $user = null, $pass = null, $db = null){
- if($host !== null) self::$host = $host;
- if($user !== null) self::$user = $user;
- if($pass !== null) self::$pass = $pass;
- if($db !== null) self::$db = $db;
- $pdo = &self::$pdo;
- if($pdo && $host === null) return;
- $dsn = sprintf('mysql:host=%s;dbname=%s;charset=%s', self::$host, self::$db, self::$charset);
- $options = array(
- PDO::MYSQL_ATTR_INIT_COMMAND => sprintf('SET NAMES %s', self::$charset)
- );
- $pdo = new PDO($dsn, self::$user, self::$pass, $options);
- $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
- $pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
- }
- /**
- * Runs a prepared query with parameters. Parameter keys in the query must be prefixed
- * with : (e.g 'SELECT * FROM `table` WHERE `name` = :name')
- * @param string $query MySQL query
- * @param array $params optional Key/value array
- * @return object
- */
- static function query($query, $params = null){
- # Add SQL_CALC_FOUND_ROWS is missing from a SELECT query
- if(!preg_match('/^\s+SELECT\s+SQL_CALC_FOUND_ROWS/i', $query)){
- $query = preg_replace('/^((\s+)?SELECT)(\s+)/i', '${1} SQL_CALC_FOUND_ROWS ${2}', $query);
- }
- $found_rows = 0;
- $affected_rows = 0;
- $num_rows = 0;
- $rows = array();
- $error = null;
- $params = (array)$params;
- $last_insert_id = null;
- try{
- $pdo = &self::$pdo;
- self::connect();
- # Get rows
- $stmt = $pdo->prepare($query);
- # Bind name/key params
- foreach($params as $key => $value){
- if($key[0] != ':') $key = ':' . $key;
- switch(gettype($value)){
- case 'integer':
- $type = PDO::PARAM_INT;
- break;
- default:
- $type = PDO::PARAM_STR;
- }
- $stmt->bindValue($key, $value, $type);
- }
- $stmt->execute();
- $rows = $stmt->fetchAll(PDO::FETCH_OBJ);
- $last_insert_id = $pdo->lastInsertId();
- $affected_rows = $stmt->rowCount();
- # Count found rows
- $stmt = $pdo->prepare("SELECT FOUND_ROWS()");
- $stmt->execute();
- $found_rows = (int)$stmt->fetchColumn(0);
- }
- catch(Exception $e){
- $error = $e->getMessage();
- }
- return (object)array(
- 'found_rows' => $found_rows,
- 'affected_rows' => $affected_rows,
- 'last_insert_id' => $last_insert_id,
- 'rows' => $rows,
- 'error' => $error,
- 'params' => $params,
- 'query' => $query
- );
- }
- }
- class db_select_paginator{
- public $classes = array('paginator');
- public $uri_pattern; // optional, e.g '/something/%s', '/results?page=%s'
- public $text_first = 'First';
- public $text_prev = 'Prev';
- public $text_next = 'Next';
- public $text_last = 'Last';
- public $wrapper_tag = 'ul';
- public $item_tag = 'li';
- private $result;
- private $margin = 3; // Page numbers to be shown either side of the current page
- /**
- * @param object $result Object returned from db::query() for a SELECT query
- * @return object
- */
- public function __construct($result){
- $this->result = $result;
- }
- /**
- * @return string URI pattern
- */
- private function default_uri_pattern(){
- $uri = preg_replace('/\?.+$/', '', $_SERVER['REQUEST_URI']);
- $qs = $_GET;
- unset($qs['page']);
- $qs = http_build_query($qs);
- $qs .= ($qs ? '&' : '') . 'page=%s';
- return sprintf('%s?%s', $uri, $qs);
- }
- /**
- * @param int $page Page number
- * @return string URI
- */
- public function uri($page){
- $pattern = (isset($this->uri_pattern) ? $this->uri_pattern : $this->default_uri_pattern());
- return sprintf($pattern, $page);
- }
- /**
- * @param int $page Page number
- * @param string $text optional Link text
- * @param string HTML
- */
- private function render_page_link($page, $text = null){
- $current_page = $this->current_page();
- $classes = array();
- if($text === null) $classes[] = sprintf('paginator-page-%s', $page);
- if($text !== null) $classes[] = sprintf('paginator-%s', preg_replace('/[^a-z0-9]{1,}/i', '-', strtolower($text)) );
- if($text === null){
- if($page == 1) $classes[] = 'paginator-numbered-first';
- if($page == $this->total_pages()) $classes[] = 'paginator-numbered-last';
- $text = $page;
- }
- if($current_page == $page) $classes[] = 'paginator-active';
- $class = implode(' ', $classes);
- $uri = $this->uri($page);
- return sprintf('<%s class="%s"><a href="%s">%s</a></%s>', $this->item_tag, $class, $uri, $text, $this->item_tag);
- }
- /**
- * @return string HTML
- */
- private function render_page_filler(){
- return '<li class="paginator-page-filler">...</li>';
- }
- /**
- * Uses the 'limit' parameter passed to a query and the number of rows found to calculate the
- * total number of pages
- * @return int
- */
- public function total_pages(){
- return ceil($this->result->found_rows / $this->result->params['limit']);
- }
- /**
- * Derives the current page from the 'offset' and 'limit' parameters that were used in the SELECT query
- * @return int
- */
- public function current_page(){
- return (int)($this->result->params['offset'] / $this->result->params['limit']) + 1;
- }
- /**
- * @return string HTML
- */
- public function render(){
- $total_pages = $this->total_pages();
- $current_page = $this->current_page();
- $start_page = $current_page - $this->margin;
- if($start_page < 1) $start_page = 1;
- $end_page = $current_page + $this->margin;
- if($end_page > $total_pages) $end_page = $total_pages;
- $class = implode(' ', $this->classes);
- $output = sprintf('<%s class="%s">', $this->wrapper_tag, $class);
- $output .= $this->render_page_link(1, $this->text_first);
- if($current_page > 1) $output .= $this->render_page_link($current_page - 1, $this->text_prev);
- if($start_page > 1) $output .= $this->render_page_filler();
- for($i = $start_page; $i <= $end_page; $i++){
- $output .= $this->render_page_link($i);
- }
- if($end_page < $total_pages) $output .= $this->render_page_filler();
- if($current_page < $total_pages) $output .= $this->render_page_link($current_page + 1, $this->text_next);
- $output .= $this->render_page_link($total_pages, $this->text_last);
- $output .= sprintf('</%s>', $this->wrapper_tag);
- return $output;
- }
- /**
- * Alias for the render() method
- * @return string HTML
- */
- public function __toString(){
- return $this->render();
- }
- }
- // ----------------------------------------- Usage -----------------------------------------
- db::connect('localhost', 'dev', 'password', 'test_db');
- $current_page = (isset($_GET['page']) ? (int)$_GET['page'] : 1);
- $per_page = 5;
- $params = array(
- 'offset' => $per_page * ($current_page - 1),
- 'limit' => $per_page
- );
- $result = db::query('SELECT * FROM `things` LIMIT :limit OFFSET :offset', $params);
- $paginator = new db_select_paginator($result);
- echo $paginator;
- foreach($result->rows as $row){
- echo sprintf('<p>#%s: %s</p>', $row->id, $row->name);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement