Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Clase de trabajo sql.
- *
- * @author Abraham Cruz Sustaita (abraham.sustaita@gmail.com)
- * @access Private
- * @version 1.0.0
- * @package Core
- * @todo Fix CoreDB for only let one instance of the class.
- *
- * Clase que facilita el trabajo sql usando métodos que retornan los datos necesarios como tablas en la BD, campos, flags de los campos.
- *
- * Ejemplo de uso:
- * $db = new Db ( null, 'test' );
- *
- * Select simple
- * $db->select('testaa','id,name',array('and','id|=|1'));
- * print_r($db->result);
- *
- * Select con función q
- * $db->q('select name from testaa');
- * print_r($db->res->fetch());
- * while($row = $db->res->fetch())
- * print_r($row);
- * $db->q('select name from testaa');
- * echo $db->fetchOne();
- *
- * Insert simple
- * echo $db->insert ( 'testaa', 'name=\'algo\'' );
- *
- * Update
- * echo $db->insert ( 'testaa', 'name=\'ponle algo111\', Id=99','id=99' );
- *
- *
- */
- class Core_Db extends Core_Db_Singleton implements Core_Gral {
- /**
- * Constructor que solo permite una instancia de la clase para evitar multiples conecciones a la base
- *
- * @param string $host
- * @param string $db
- * @param string $user
- * @param string $pass
- * @param string $engine
- * @return Object
- */
- public function __construct($host = null, $db = null, $user = null, $pass = null, $engine = null) {
- if (! parent::$instance) {
- parent::__construct ( $host, $db, $user, $pass, $engine );
- } else {
- return parent::$instance;
- }
- return false;
- }
- /**
- * Evita el clonado del objeto
- *
- */
- public function __clone() {
- trigger_error ( 'Clone is not allowed.', E_USER_ERROR );
- }
- /**
- * Crea métodos en tiempo de ejecución
- *
- * @param string $method
- * @param mixed $args
- */
- public function __call($method, $args) {
- //TODO Load methods on the fly
- }
- /**
- * Evita error fatal al hacer echo $obj
- *
- * @return string
- */
- public function __toString() {
- return '';
- }
- }
- /**
- * Clase de trabajo sql.
- *
- */
- class Core_Db_Singleton extends PDO {
- /**
- * Objeto con datos de las consultas sql
- *
- * @var Object
- */
- public $data;
- /**
- * Array con resultado de consultas sql
- *
- * @var array
- */
- public $result;
- /**
- * String que contiene un arreglo xml
- *
- * @var string
- */
- public $xml;
- /**
- * String que contiene una tabla xls
- *
- * @var string
- */
- public $xls;
- /**
- * Define si se agregegará ND a los xml armados
- *
- * @var bool
- */
- public $nd = true;
- /**
- * Objeto PDO con query
- *
- * @var Object
- */
- protected $res;
- /**
- * Tabla de última consulta sql
- *
- * @var string
- */
- protected $_table = null;
- /**
- * Número de página
- *
- * @var int
- */
- protected $_page = null;
- /**
- * Contraseña de Base de Datos
- *
- * @var string
- */
- protected $_user = USER;
- /**
- * Password de base de datos
- *
- * @var string
- */
- protected $_pass = PASSWORD;
- /**
- * Host
- *
- * @var string
- */
- protected $_host = HOST;
- /**
- * Base de datos
- *
- * @var string
- */
- protected $_db = DB;
- /**
- * Tipo de motor sql
- *
- * @var string
- */
- protected $_engine = 'mysql';
- /**
- * String con el query
- *
- * @var string
- */
- protected $_sql = null;
- /**
- * Propiedades a las que no se podrá acceder mediante su contenido
- *
- * @var array
- */
- private $_private = array ('_private' => true );
- /**
- * Propiedades que no podrán ser seteadas
- *
- * @var array
- */
- private $_notSet = array ('_private' => true, '_notSet' => true );
- /**
- * Objeto con funciones
- *
- * @var Object
- */
- private $_functions;
- /**
- * Instancia de la clase para solo usar una instancia
- *
- * @var Object
- */
- protected static $instance;
- //Métodos públicos
- /**
- * Select que regresa un array asociativo con los datos arrojados por la consulta sql.
- *
- * @param string $table
- * @param string $data
- * @param mixed $where
- * @param int $limit
- * @param int $page
- * @param string $order
- */
- public function select($table, $data = null, $where = null, $limit = null, $page = 1, $order = null) {
- unset ( $this->_sql );
- unset ( $this->res );
- $data = ($data) ? $data : '*';
- $this->_table = $table;
- $this->_page = $page;
- $q = 'SELECT SQL_CALC_FOUND_ROWS ' . $data . ' FROM ';
- $q .= $table . ' ';
- $q .= ($where) ? $this->_setWhere ( $where ) : '';
- $q .= ($order) ? ' ORDER BY ' . $order : '';
- $q .= ($limit) ? ' LIMIT ' . (($page - 1) * $limit) . ',' . $limit : '';
- $this->_sql = $q;
- try {
- $this->res = $this->query ( $q );
- if (! is_object ( $this->res ))
- throw new PDOException ( );
- } catch ( PDOException $e ) {
- $this->saveLogErr ( $e );
- exit ();
- }
- $this->setFetch ();
- $aryData = array ();
- $count = 0;
- while ( $ary = $this->res->fetch () ) {
- $aryData [] = $ary;
- ++ $count;
- }
- $this->result = $aryData;
- return $count;
- }
- /**
- * Ejecuta el query que este guardado en memoria y lo guarda en el array. Devuelve el número de rows
- *
- * @return int
- */
- public function asArray() {
- $aryData = array ();
- $count = 0;
- while ( $ary = $this->res->fetch () ) {
- $aryData [] = $ary;
- ++ $count;
- }
- $this->result = $aryData;
- return $count;
- }
- /**
- * Deprecated.
- * Ejecuta el query que este guardado en memoria y lo guarda en el array. Devuelve el número de rows
- *
- * @return int
- */
- public function personalized() {
- $this->asArray ();
- }
- /**
- * Prepara un query para ser usado
- *
- * @param string $q
- */
- public function q($q) {
- unset ( $this->_sql );
- unset ( $this->res );
- $this->_sql = $q;
- $qS = str_replace ( "\n", ' ', $q );
- $aryQS = explode ( ' ', $qS );
- foreach ( $aryQS as $key => $txt ) {
- $txt = str_replace ( ' ', '', $txt );
- if (strtoupper ( $txt ) == 'FROM') {
- $this->_table = $aryQS [$key + 1];
- break;
- }
- }
- try {
- $this->res = $this->query ( $q );
- if (! is_object ( $this->res ))
- throw new PDOException ( );
- } catch ( PDOException $e ) {
- $this->saveLogErr ( $e );
- exit ();
- }
- $this->setFetch ();
- }
- /**
- * Regresa el único valor obtenido por el método select
- *
- * @return mixed
- */
- public function fetchOne() {
- $ary = $this->res->fetch ();
- $aryKeys = array_keys ( $ary );
- $ret = $ary [$aryKeys [0]];
- return $ret;
- }
- /**
- * Método que hace inserción a la BD.
- *
- * Se le pasan como parámetros la tabla, los datos, el where (en forma de array opcional: array ('tipo', 'field|condicion|valor', 'field|condicion|valor')),
- * y el límite (int opcional).
- * Los tipos de where es tipo: 'AND', 'OR', 'PERSONALIZED'
- * Los tipos de condicion son: =, >=, <=, BETWEEN, IN, NOT IN. En caso de ser BETWEEN el tercer campo despues de | es
- * ('condicion inicial') and ('condicion final')
- * Regresa el id insertado o true en caso de ser update
- *
- * @param string $table
- * @param string $data
- * @param array $where
- * @param int $limit
- * @return int
- */
- public function insert($table, $data, $where = null, $limit = null) {
- $q = ($where) ? 'UPDATE ' : 'INSERT ';
- $q .= $table . ' SET ' . $data;
- $q .= ($where) ? ' WHERE ' . $where : '';
- $q .= ($limit) ? ' LIMIT ' . $limit : '';
- //echo $q; exit;
- unset ( $this->_sql );
- unset ( $this->res );
- $this->_sql = $q;
- try {
- $this->res = $this->query ( $q );
- if (! is_object ( $this->res ))
- throw new PDOException ( );
- } catch ( PDOException $e ) {
- echo '<br>El siguiente insert no es válido:</br>
- <strong>' . $q . '</strong><br />';
- $this->saveLogErr ( $e );
- return false;
- }
- $this->res->fetch ();
- $id = 'SELECT LAST_INSERT_ID()';
- $idQ = $this->query ( $id );
- $idA = $idQ->fetch ();
- return ($where != null) ? true : $idA ['LAST_INSERT_ID()'];
- }
- /**
- * Método que agrega al objeto data los campos de la tabla.
- *
- * @param string $table
- */
- public function fields($table = null) {
- unset ( $this->_sql );
- unset ( $this->res );
- $table = (! empty ( $this->_table )) ? $this->_table : (($table) ? $table : null);
- if ($table != null) {
- //echo 'SHOW FULL COLUMNS FROM ' . $table ;
- $this->q ( 'SHOW FULL COLUMNS FROM ' . $table );
- $fields = array ();
- while ( $field = $this->res->fetch () ) {
- $fields [] = $field;
- //print_r ($field);
- }
- $this->data->fields = $fields;
- }
- }
- /**
- * Revisa si la tabla se encuentra en la base de datos. Si la encuentra, lista los campos que tiene.
- *
- * @param string $table
- * @return int
- */
- public function checkTable($table = null) {
- $table = ($table == null) ? $this->_table : $table;
- $this->listTables ();
- foreach ( $this->data->tables as $tableExist ) {
- if ($tableExist == $table) {
- $this->fields ();
- return true;
- break;
- }
- }
- return false;
- }
- /**
- * Método que busca el total de la última consulta sql SIN limites
- *
- * @return int
- */
- public function getTot() {
- unset ( $this->_sql );
- unset ( $this->res );
- $this->q ( 'SELECT FOUND_ROWS()' );
- $ret = $this->fetchOne ();
- $this->data->tot = $ret;
- return $ret;
- }
- /**
- * Regresa un xml formado con el nombre de la tabla en la que se ejecuto la consulta
- *
- * @return string
- */
- public function xml() {
- header ( "Content-type: application/xml" );
- $xml = '<query>';
- foreach ( $this->result as $aryResult ) {
- $xml .= '<' . $this->_table . ' ';
- foreach ( $aryResult as $field => $data ) {
- $xml .= ' ' . $field . '="' . $this->_clean ( $data ) . '" ';
- }
- $xml .= '/>';
- }
- if ($this->nd == true) {
- $xml .= '<' . $this->_table . ' ';
- foreach ( $aryResult as $field => $data ) {
- $xml .= ' ' . $field . '="ND" ';
- }
- $xml .= '/>';
- }
- $xml .= '</query>';
- $this->xml = $xml;
- return $xml;
- }
- /**
- * Genera un archivo de excel con la consulta previa
- *
- * @return string
- */
- public function xls($aryHead = null, $headers = true) {
- //echo 'tsss';
- if ($headers) {
- $this->_functions->excel ( $this->_table . '.xls' );
- }
- $xls = '<table>
- <tr>';
- $aryHead = ($aryHead) ? $aryHead : array_keys ( $this->result [0] );
- foreach ( $aryHead as $head ) {
- $xls .= '<td>' . utf8_decode ( $head ) . '</td>';
- }
- $xls .= '</tr>';
- foreach ( $this->result as $aryFields ) {
- $xls .= '<tr>';
- foreach ( $aryFields as $field ) {
- $xls .= '<td>' . utf8_decode ( $field ) . '</td>';
- }
- $xls .= '</tr>';
- }
- $xls .= '</table>';
- $this->xls = $xls;
- return $xls;
- }
- /**
- * Método que obtiene la llave primaria de una tabla
- *
- * @param string $table
- */
- public function getPrimary($table = null) {
- $this->fields ( $table );
- foreach ( $this->data->fields as $aryField ) {
- if ($aryField ['Key']) {
- $this->data->primary = $aryField ['Field'];
- break;
- }
- }
- }
- //Métodos privados
- /**
- * Genera un string where a partir de un array.
- *
- * El primer valor del array es el tipo de where - and, or, like y personal - y los demás son el where dividido por | teniendo tres valores:
- * campo|condicion|valor. Si la condición es between el valor deberá ser dos fechas en formato sql.
- *
- * @param array $aryWhere
- * @return string
- */
- private function _setWhere($aryWhere) {
- $sql = '';
- if (is_string ( $aryWhere )) {
- return ' WHERE ' . $aryWhere;
- }
- //print_r($aryWhere);
- if (count ( $aryWhere ) > 0) {
- $sql .= 'WHERE ';
- if (strtoupper ( $aryWhere [0] ) == "LIKE") {
- unset ( $aryWhere [0] );
- if (strtoupper ( $aryWhere [1] ) == "AND") {
- $and = " AND ";
- } else {
- $and = " OR ";
- }
- unset ( $aryWhere [1] );
- $totWhere = count ( $aryWhere );
- $iW = 1;
- foreach ( $aryWhere as $k => $j ) {
- if ($iW == $totWhere) {
- $sql .= " " . $k . " LIKE '%" . $j . "%' ";
- } else {
- $sql .= " " . $k . " LIKE '%" . $j . "%' " . $and;
- }
- $iW ++;
- }
- } else if (strtoupper ( $aryWhere [0] ) == "AND" || strtoupper ( $aryWhere [0] ) == "OR") {
- $and = (strtoupper ( $aryWhere [0] ) == 'AND') ? 'AND' : 'OR';
- unset ( $aryWhere [0] );
- $totWhere = count ( $aryWhere );
- $iW = 1;
- foreach ( $aryWhere as $k => $j ) {
- $whereB = explode ( "|", $j );
- if ($iW == $totWhere) {
- if (strtoupper ( $whereB [1] ) == 'LIKE') {
- $sql .= " " . $whereB [0] . ' ' . $whereB [1] . " '%" . $whereB [2] . "%' ";
- } else if (strtoupper ( $whereB [1] ) == 'IN' || strtoupper ( $whereB [1] ) == 'NOT IN' || strtoupper ( $whereB [1] ) == 'BETWEEN')
- $sql .= " " . $whereB [0] . ' ' . $whereB [1] . " " . $whereB [2] . " ";
- else
- $sql .= " " . $whereB [0] . $whereB [1] . "'" . $whereB [2] . "' ";
- } else {
- if (strtoupper ( $whereB [1] ) == 'IN' || strtoupper ( $whereB [1] ) == 'NOT IN' || strtoupper ( $whereB [1] ) == 'BETWEEN') {
- $sql .= " " . $whereB [0] . ' ' . $whereB [1] . " " . $whereB [2] . " $and ";
- } else if (strtoupper ( $whereB [1] ) == 'LIKE')
- $sql .= " " . $whereB [0] . ' ' . $whereB [1] . " '%" . $whereB [2] . "%' $and ";
- else
- $sql .= " " . $whereB [0] . $whereB [1] . "'" . $whereB [2] . "' $and ";
- }
- $iW ++;
- }
- } else if (empty ( $aryWhere [0] )) {
- $whereB = explode ( "|", $aryWhere [1] );
- if (strtoupper ( $whereB [1] ) == 'IN' || strtoupper ( $whereB [1] ) == 'NOT IN' || strtoupper ( $whereB [1] ) == 'LIKE' || strtoupper ( $whereB [1] ) == 'BETWEEN')
- $sql .= " " . $whereB [0] . ' ' . $whereB [1] . " " . $whereB [2] . " ";
- else
- $sql .= " " . $whereB [0] . $whereB [1] . "'" . $whereB [2] . "' ";
- } else if (strtoupper ( $aryWhere [0] ) == "PERSONAL") {
- unset ( $aryWhere [0] );
- $sql .= $aryWhere [1];
- }
- }
- return $sql;
- }
- /**
- * Intenta conección a BD o guarda error
- *
- */
- protected function _connect() {
- try {
- parent::__construct ( "$this->_engine:host=$this->_host;dbname=$this->_db", $this->_user, $this->_pass );
- } catch ( PDOException $e ) {
- Core_Db::saveLogErr ( $e );
- }
- try {
- $this->query ( "SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'" );
- } catch ( PDOException $e ) {
- Core_Db::saveLogErr ( $e );
- }
- }
- /**
- * Define el tipo de fetch a usar, assoc por default
- *
- * @param string $mode
- */
- protected function setFetch($mode = 'FETCH_ASSOC') {
- try {
- if (! is_object ( $this->res )) {
- throw new PDOException ( );
- }
- if ($mode == 'FETCH_ASSOC')
- $this->res->setFetchMode ( PDO::FETCH_ASSOC );
- } catch ( PDOException $e ) {
- $this->saveLogErr ( $e );
- }
- }
- /**
- * Método que guarda el log de errores de conecciones y demás
- *
- * @param PDOException $e
- * @param bool $show
- */
- private function saveLogErr($e, $show = true) {
- $err_repo = error_reporting ();
- error_reporting ( $err_repo );
- if ($show == true && $err_repo != 0) {
- echo '<p>Se ha detectado el siguiente error y es imposible continuar:<br />
- <strong>' . $e->getMessage () . '</strong>
- </p>
- La traza para el error es la siguiente:<br />
- ';
- echo '<strong>' . str_replace ( "\n", '<br />' . "\n", $e->getTraceAsString () ) . '</strong>';
- echo '
- <br />
- <br>La linea del error fue:<br />
- <strong>' . $e->getLine () . '</strong><br />
- El query fue: ' . $this->_sql . '
- ';
- }
- //TODO Guardar en archivo
- }
- protected function _clean($data) {
- $aDirty = array ();
- $aDirty ['&'] = '&';
- foreach ( $aDirty as $dirty => $clean ) {
- $data = str_replace ( $dirty, $clean, $data );
- }
- return $data;
- }
- /**
- * Método que lista las tablas de la base de datos
- *
- */
- protected function listTables() {
- $q = "SHOW TABLES";
- unset ( $this->_sql );
- unset ( $this->res );
- $this->_sql = $q;
- try {
- $this->res = parent::query ( $q );
- } catch ( PDOException $e ) {
- print_r ( $e );
- }
- if (! is_object ( $this->res ))
- echo 'El siguiente query no es válido: ' . $q;
- $this->setFetch ();
- while ( $list = $this->res->fetch () ) {
- $this->data->tables [] = $list ['Tables_in_' . $this->_db];
- }
- }
- //Métodos mágicos
- /**
- * Constructor de la clase; recibe como parametros host, db, user, pass y engine. Por default son localhost, null, root, null y mysql
- *
- * @param string $host
- * @param string $db
- * @param string $user
- * @param string $pass
- * @param string $engine
- */
- public function __construct($host = null, $db = null, $user = null, $pass = null, $engine = null) {
- $this->_user = ($user) ? $user : $this->_user;
- $this->_pass = ($pass) ? $pass : $this->_pass;
- $this->_host = ($host) ? $host : $this->_host;
- $this->_db = ($db) ? $db : $this->_db;
- $this->_engine = ($engine) ? $engine : $this->_engine;
- $this->data = new stdClass ( );
- $this->_connect ();
- $this->_functions = new Core_Functions ( );
- }
- /**
- * Método __get, recibe como parámetro la propiedad a obtener
- *
- * @param string $prop
- * @return mixed
- */
- public function __get($prop) {
- $ret = null;
- if ($this->$prop && ! isset ( $this->_private [$prop] ))
- $ret = $this->$prop;
- return $ret;
- }
- /**
- * Método __set, recibe la variable y el valor a setear
- *
- * @param string $prop
- * @param mixed $var
- */
- public function __set($prop, $var) {
- if (! isset ( $this->_notSet [$prop] ))
- $this->$prop = $var;
- }
- public function __destruct() {
- unset ( $this );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement