Created
October 24, 2018 07:51
-
-
Save renzoster/9ad04002de3c1efad4b9bcbb7d8cf3df to your computer and use it in GitHub Desktop.
DB Class like WordPress DB
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 | |
class db{ | |
protected $con = false; | |
public function __destruct(){ | |
return null; | |
} | |
public function connect($dbhost, $dbname, $dbuser, $dbpass){ | |
try{ | |
$this->con = new PDO(sprintf('mysql:host=%s;dbname=%s;charset=utf8', $dbhost, $dbname), $dbuser, $dbpass); | |
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
} catch (PDOException $e) { | |
//echo 'Falló la conexión: ' . $e->getMessage(); | |
return false; | |
} | |
return $this->con; | |
} | |
public function close(){ | |
$this->con = false; | |
} | |
public function count($tablename, $conditions = NULL, $values = NULL){ | |
if( empty($tablename) || !is_string($tablename) ) | |
return false; | |
$sql = sprintf('SELECT COUNT(*) AS count FROM `%s`', $tablename); | |
$conditions = trim($conditions); | |
if( !is_null($conditions) ){ | |
$tokens = explode(' ', $conditions); | |
$method = array('ORDER', 'LIMIT', 'JOIN', 'LEFT', 'INNER', 'RIGHT', 'OUTER'); | |
if( in_array($tokens[0], $method) ){ | |
$sql .= ' '.str_replace('?', '%s', $conditions); | |
} else { | |
$sql .= ' WHERE '.str_replace('?', '%s', $conditions); | |
} | |
if( !is_null($values) ){ | |
if( is_array($values) ){ | |
$sql = $this->prepare($sql, $values); | |
} else { | |
$args = func_get_args(); | |
array_shift($args); | |
array_shift($args); | |
$sql = $this->prepare($sql, $args); | |
} | |
} | |
} | |
$res = $this->get_results( $sql ); | |
if( $res == FALSE ) return false; | |
return $res[0]->count; | |
} | |
public function dispense($tablename, $id=NULL){ | |
if( empty($tablename) || !is_string($tablename) ) | |
return false; | |
$new = new db(); | |
$new->get_primary_key($tablename); | |
if( !is_null($id) ){ | |
$res = $new->get_results( sprintf('SELECT * FROM `%s` WHERE `%s`="%s" LIMIT 1', $tablename, $new->primary_key, $id) ); | |
if( $res == FALSE ) | |
return false; | |
foreach($new->cols as $col){ | |
$new->$col = $res[0]->$col; | |
} | |
} | |
return $new; | |
} | |
public function find($tablename, $conditions = NULL, $values = NULL){ | |
if( empty($tablename) || !is_string($tablename) ) | |
return false; | |
$sql = sprintf('SELECT * FROM `%s`', $tablename); | |
if( !is_null($conditions) ){ | |
$conditions = trim($conditions); | |
$tokens = explode(' ', $conditions); | |
$method = array('ORDER', 'LIMIT', 'JOIN', 'LEFT', 'INNER', 'RIGHT', 'OUTER'); | |
if( in_array($tokens[0], $method) ){ | |
$sql .= ' '.str_replace('?', '%s', $conditions); | |
} else { | |
$sql .= ' WHERE '.str_replace('?', '%s', $conditions); | |
} | |
if( !is_null($values) ){ | |
if( is_array($values) ){ | |
$sql = $this->prepare($sql, $values); | |
} else { | |
$args = func_get_args(); | |
array_shift($args); | |
array_shift($args); | |
$sql = $this->prepare($sql, $args); | |
} | |
} | |
} | |
$res = $this->get_results( $sql ); | |
if( $res == FALSE ) return false; | |
return $res; | |
} | |
public function query($query){ | |
if(!$this->con){ | |
if( $this->connect() == FALSE ) | |
return false; | |
} | |
$query = apply_filters( 'query', $query ); | |
try{ | |
$this->res = $this->con->query($query); | |
if ( preg_match( '/^\s*(select)\s/i', $query ) ) { | |
$this->cols = array(); | |
for($i = 0; $i < $this->res->columnCount(); ++$i){ | |
$col = $this->res->getColumnMeta($i); | |
$this->cols[] = $col['name']; | |
if( in_array('primary_key', $col['flags']) ){ | |
$this->primary_key = $col['name']; | |
} | |
} | |
} elseif ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) { | |
$this->last_insert = $this->con->lastInsertId(); | |
if( isset($this->primary_key) && isset($this->table_name) ){ | |
$primary = $this->primary_key; | |
$this->$primary = $this->last_insert; | |
} | |
return $this->last_insert; | |
} | |
return $this->res->rowCount(); | |
} catch( PDOException $e ){ | |
return false; | |
} | |
} | |
public function last_id(){ | |
return $this->con->lastInsertId(); | |
} | |
public function num_rows(){ | |
return $this->res->rowCount(); | |
} | |
public function get_column_names($table){ | |
if(!$this->con) | |
$this->connect(); | |
$rs = $this->con->query(sprintf('SELECT * FROM %s LIMIT 0', $table)); | |
for ($i = 0; $i < $rs->columnCount(); $i++) { | |
$col = $rs->getColumnMeta($i); | |
$columns[] = $col['name']; | |
} | |
return $rs; | |
} | |
public function get_var($query = null){ | |
$res = $this->get_results($query); | |
if( !$res ) | |
return false; | |
$first = (array)reset($res); | |
return reset($first); | |
} | |
public function get_result($query = null){ | |
return $this->get_results($query); | |
} | |
public function get_results($query = null){ | |
if(!is_null($query)){ | |
if( !$this->query($query) ) | |
return false; | |
} | |
$result = array(); | |
while( $res = $this->res->fetchObject() ){ | |
$result[] = $res; | |
} | |
return $result; | |
} | |
public function get_primary_key($tablename){ | |
if( empty($tablename) || !is_string($tablename) ) | |
return false; | |
$this->table_name = $tablename; | |
$this->query(sprintf('SELECT * FROM %s LIMIT 0', $tablename)); | |
return $this->primary_key; | |
} | |
public function insert($table, $data){ | |
$fields = array_keys($data); | |
$formatted_fields = array(); | |
foreach($fields as $field){ | |
$formatted_fields[] = '%s'; | |
} | |
$sql = 'INSERT INTO `'.$table.'` (`'.implode('`,`', $fields).'`) VALUES ('. implode(',', $formatted_fields).')'; | |
return $this->query($this->prepare($sql, $data)); | |
} | |
public function last_query(){ | |
if( !isset($this->res) || $this->res == FALSE ) | |
return false; | |
return $this->res->queryString; | |
} | |
public function remove(){ | |
if( !isset($this->primary_key) || !isset($this->table_name) ) | |
return false; | |
$primary = $this->primary_key; | |
if( isset($this->$primary) || !empty($this->$primary) || !is_null($this->$primary) ){ | |
return $this->delete($this->table_name, array($primary => $this->$primary)); | |
} | |
return false; | |
} | |
public function save(){ | |
$primary = $this->primary_key; | |
$data = array(); | |
foreach($this->cols as $col){ | |
if( isset($this->$col) ) | |
$data[$col] = $this->$col; | |
} | |
if( isset($this->$primary) ){ | |
return $this->update($this->table_name, $data, array($primary => $this->$primary)); | |
} else { | |
return $this->insert($this->table_name, $data); | |
} | |
} | |
public function update($table, $data, $where){ | |
$bits = $wheres = array(); | |
foreach($data as $key => $value){ | |
$form = '%s'; | |
$bits[] = "`$key` = {$form}"; | |
} | |
foreach($where as $key => $value){ | |
$form = '%s'; | |
$wheres[] = "`$key` = {$form}"; | |
} | |
$sql = sprintf('UPDATE `%s` SET %s WHERE %s', $table, implode(', ', $bits), implode(' AND ', $wheres)); | |
return $this->query( $this->prepare($sql, array_merge(array_values($data), array_values($where))) ); | |
} | |
public function delete($table, $where, $where_format = null){ | |
if(!is_array($where)) | |
return false; | |
$where = $this->process_fields( $table, $where, $where_format ); | |
if ( false === $where ) { | |
return false; | |
} | |
$conditions = $values = array(); | |
foreach($where as $field => $value){ | |
if ( is_null( $value['value'] ) ) { | |
$conditions[] = "`$field` IS NULL"; | |
continue; | |
} | |
$conditions[] = "`$field` = " . $value['format']; | |
$values[] = $value['value']; | |
} | |
$conditions = implode( ' AND ', $conditions ); | |
$sql = "DELETE FROM `$table` WHERE $conditions"; | |
return $this->query($this->prepare($sql, $values)); | |
} | |
public function prepare($query, $args){ | |
if(is_null($query)) | |
return; | |
$args = func_get_args(); | |
array_shift( $args ); | |
if ( isset( $args[0] ) && is_array($args[0]) ) | |
$args = $args[0]; | |
$query = str_replace( "'%s'", '%s', $query ); | |
$query = str_replace( '"%s"', '%s', $query ); | |
$query = preg_replace( '|(?<!%)%f|' , '%F', $query ); | |
$query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); | |
array_walk( $args, array($this, 'escape_by_ref') ); | |
return @vsprintf($query, $args); | |
} | |
public function escape_by_ref(&$string){ | |
if( !is_float($string) ) | |
$string = $this->_real_escape( $string ); | |
} | |
private function _real_escape($string){ | |
if($this->con) | |
return substr($this->con->quote($string), 1, -1); | |
return addslashes($string); | |
} | |
protected function process_fields( $table, $data, $format ) { | |
$data = $this->process_field_formats( $data, $format ); | |
if ( false === $data ) { | |
return false; | |
} | |
return $data; | |
} | |
protected function process_field_formats( $data, $format ) { | |
$formats = $original_formats = (array) $format; | |
foreach ( $data as $field => $value ) { | |
$value = array( | |
'value' => $value, | |
'format' => '%s', | |
); | |
if ( ! empty( $format ) ) { | |
$value['format'] = array_shift( $formats ); | |
if ( ! $value['format'] ) { | |
$value['format'] = reset( $original_formats ); | |
} | |
} elseif ( isset( $this->field_types[ $field ] ) ) { | |
$value['format'] = $this->field_types[ $field ]; | |
} | |
$data[ $field ] = $value; | |
} | |
return $data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment