DB class for CodeIgniter
It's a simple and useful MySQL DB class.
I modify it from WordPress2.5.1 wp-db.php
It also automatic load DB config from CI config file.
Author: http://www.21andy.com
Usage:
just put it in your CI app library folder, usually in system/application/libraries
and name Db.php
now , you can load the library anywhere, or set it automatic load in autoload config file
$this->load->library('db');
turn SAVE QUERIES on
$this->db->save_query(true);
I think these method is good than CI database, only ONE line code.
$this->db->get_var($sql);
$this->db->get_row($sql);
$this->db->get_col($sql);
$this->db->get_results($sql);
$this->db->get_row($sql);
$this->db->get_col($sql);
$this->db->get_results($sql);
enjoy it!!!
anyway, sorry for my poor english.
Db.php
<?php
/**
*@Filename: Db.php
*@Version : 1.0
*@Author : Andy
*@Website: http://www.21andy.com/
*@Update : 2008-06-07
*@Content : DB class for CodeIgniter
* ORIGINAL CODE FROM:
* Justin Vincent ([email protected])
* http://php.justinvincent.com
*/
define('OBJECT', 'OBJECT', true);
define('OBJECT_K', 'OBJECT_K', false);
define('ARRAY_A', 'ARRAY_A', false);
define('ARRAY_N', 'ARRAY_N', false);
class Db {
var $show_errors = false;
var $suppress_errors = false;
var $last_error = '';
var $num_queries = 0;
var $last_query;
var $col_info;
var $queries;
var $prefix = '';
var $ready = false;
var $charset;
var $collate;
var $savequeries = true;
function Db() {
include(APPPATH.'config/database'.EXT);
if ( ! isset($db) OR count($db) == 0)
{
show_error('No database connection settings were found in the database config file.');
}
if ( ! isset($active_group) OR ! isset($db[$active_group]))
{
show_error('You have specified an invalid database connection group.');
}
$params = $db[$active_group];
$this->dbuser = $params['username'];
$this->dbpassword = $params['password'];
$this->dbname = $params['database'];
$this->dbhost = $params['hostname'];
$this->charset = $params['char_set'];
$this->collate = $params['dbcollat'];
register_shutdown_function(array(&$this, "__destruct"));
if ( defined('DEBUG') and DEBUG == true )
$this->show_errors();
if ( defined('DB_CHARSET') )
$this->charset = DB_CHARSET;
if ( defined('DB_COLLATE') )
$this->collate = DB_COLLATE;
$this->dbh = @mysql_connect($this->dbhost, $this->dbuser, $this->dbpassword, true);
if (!$this->dbh) {
$this->bail("can't connect to db");
return;
}
$this->ready = true;
if( !empty($this->charset) )
mysql_query("SET character_set_connection={$this->charset}, character_set_results={$this->charset}, character_set_client=binary");
if($this->version() > '5.0.1')
mysql_query("SET sql_mode=''");
$this->select($this->dbname);
}
function __destruct() {
return true;
}
function version() {
return mysql_get_server_info();
}
function select($db) {
if ([email protected]mysql_select_db($db, $this->dbh)) {
$this->ready = false;
$this->bail("select db error $db");
return;
}
}
function save_query($enable = false) {
$this->savequeries = $enable;
}
function escape($string) {
return addslashes( $string );
}
function escape_by_ref(&$s) {
$s = $this->escape($s);
}
function prepare($args=NULL) {
if ( NULL === $args )
return;
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
$query = str_replace('"%s"', '%s', $query); // doublequote unquoting
$query = str_replace('%s', "'%s'", $query); // quote the strings
array_walk($args, array(&$this, 'escape_by_ref'));
return @vsprintf($query, $args);
}
function print_error($str = '') {
if (!$str) $str = mysql_error($this->dbh);
if ( $this->suppress_errors )
return false;
$error_str = "Database error $str for query $this->last_query";
if ( $caller = $this->get_caller() )
$error_str .= " made by $caller";
$log_error = true;
if ( ! function_exists('error_log') )
$log_error = false;
$log_file = @ini_get('error_log');
if ( !empty($log_file) && ('syslog' != $log_file) && !is_writable($log_file) )
$log_error = false;
if ( $log_error )
@error_log($error_str, 0);
// Is error output turned on or not..
if ( !$this->show_errors )
return false;
$str = htmlspecialchars($str, ENT_QUOTES);
$query = htmlspecialchars($this->last_query, ENT_QUOTES);
// If there is an error then take note of it
print "<div id='error'>
<p class='wpdberror'><strong>Database error:</strong> [$str]<br />
<code>$query</code></p>
</div>";
}
function show_errors( $show = true ) {
$errors = $this->show_errors;
$this->show_errors = $show;
return $errors;
}
function hide_errors() {
$show = $this->show_errors;
$this->show_errors = false;
return $show;
}
function suppress_errors( $suppress = true ) {
$errors = $this->suppress_errors;
$this->suppress_errors = $suppress;
return $errors;
}
function flush() {
$this->last_result = array();
$this->col_info = null;
$this->last_query = null;
}
function query($query) {
if ( ! $this->ready )
return false;
$return_val = 0;
$this->flush();
$this->func_call = "\$db->query(\"$query\")";
$this->last_query = $query;
if ($this->savequeries)
$this->timer_start();
$this->result = @mysql_query($query, $this->dbh);
++$this->num_queries;
if ($this->savequeries)
$this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
if ( $this->last_error = mysql_error($this->dbh) ) {
$this->print_error();
return false;
}
if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
$this->rows_affected = mysql_affected_rows($this->dbh);
if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
$this->insert_id = mysql_insert_id($this->dbh);
}
$return_val = $this->rows_affected;
} else {
$i = 0;
while ($i < @mysql_num_fields($this->result)) {
$this->col_info[$i] = @mysql_fetch_field($this->result);
$i++;
}
$num_rows = 0;
while ( $row = @mysql_fetch_object($this->result) ) {
$this->last_result[$num_rows] = $row;
$num_rows++;
}
@mysql_free_result($this->result);
$this->num_rows = $num_rows;
$return_val = $this->num_rows;
}
return $return_val;
}
function add_magic_quotes( $array ) {
foreach ( $array as $k => $v ) {
if ( is_array( $v ) ) {
$array[$k] = $this->add_magic_quotes( $v );
} else {
$array[$k] = $this->escape( $v );
}
}
return $array;
}
function insert($table, $data) {
$data = $this->add_magic_quotes($data);
$fields = array_keys($data);
return $this->query("INSERT INTO $table (`" . implode('`,`',$fields) . "`) VALUES ('".implode("','",$data)."')");
}
function update($table, $data, $where){
$data = $this->add_magic_quotes($data);
$bits = $wheres = array();
foreach ( array_keys($data) as $k )
$bits[] = "`$k` = '$data[$k]'";
if ( is_array( $where ) )
foreach ( $where as $c => $v )
$wheres[] = "$c = '" . $this->escape( $v ) . "'";
else
return false;
return $this->query( "UPDATE $table SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ) . ' LIMIT 1' );
}
function get_var($query=null, $x = 0, $y = 0) {
$this->func_call = "\$db->get_var(\"$query\",$x,$y)";
if ( $query )
$this->query($query);
if ( !empty( $this->last_result[$y] ) ) {
$values = array_values(get_object_vars($this->last_result[$y]));
}
return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
}
function get_row($query = null, $output = OBJECT, $y = 0) {
$this->func_call = "\$db->get_row(\"$query\",$output,$y)";
if ( $query )
$this->query($query);
else
return null;
if ( !isset($this->last_result[$y]) )
return null;
if ( $output == OBJECT ) {
return $this->last_result[$y] ? $this->last_result[$y] : null;
} elseif ( $output == ARRAY_A ) {
return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
} elseif ( $output == ARRAY_N ) {
return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
} else {
$this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
}
}
function get_col($query = null , $x = 0) {
if ( $query )
$this->query($query);
$new_array = array();
for ( $i=0; $i < count($this->last_result); $i++ ) {
$new_array[$i] = $this->get_var(null, $x, $i);
}
return $new_array;
}
function get_results($query = null, $output = OBJECT) {
$this->func_call = "\$db->get_results(\"$query\", $output)";
if ( $query )
$this->query($query);
else
return null;
if ( $output == OBJECT ) {
return $this->last_result;
} elseif ( $output == OBJECT_K ) {
foreach ( $this->last_result as $row ) {
$key = array_shift( get_object_vars( $row ) );
if ( !isset( $new_array[ $key ] ) )
$new_array[ $key ] = $row;
}
return $new_array;
} elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
if ( $this->last_result ) {
$i = 0;
foreach( $this->last_result as $row ) {
if ( $output == ARRAY_N ) {
$new_array[$i] = array_values( get_object_vars( $row ) );
} else {
$new_array[$i] = get_object_vars( $row );
}
++$i;
}
return $new_array;
}
}
}
function get_col_info($info_type = 'name', $col_offset = -1) {
if ( $this->col_info ) {
if ( $col_offset == -1 ) {
$i = 0;
foreach($this->col_info as $col ) {
$new_array[$i] = $col->{$info_type};
$i++;
}
return $new_array;
} else {
return $this->col_info[$col_offset]->{$info_type};
}
}
}
function timer_start() {
$mtime = microtime();
$mtime = explode(' ', $mtime);
$this->time_start = $mtime[1] + $mtime[0];
return true;
}
function timer_stop() {
$mtime = microtime();
$mtime = explode(' ', $mtime);
$time_end = $mtime[1] + $mtime[0];
$time_total = $time_end - $this->time_start;
return $time_total;
}
function bail($message) { // Just wraps errors in a nice header and footer
if ( !$this->show_errors ) {
$this->error = $message;
return false;
}
die($message);
}
function supports_collation() {
return ( version_compare(mysql_get_server_info($this->dbh), '4.1.0', '>=') );
}
function get_caller() {
if ( !is_callable('debug_backtrace') )
return '';
$bt = debug_backtrace();
$caller = '';
foreach ( $bt as $trace ) {
if ( @$trace['class'] == __CLASS__ )
continue;
elseif ( strtolower(@$trace['function']) == 'call_user_func_array' )
continue;
$caller = $trace['function'];
break;
}
return $caller;
}
}
/**
*@Filename: Db.php
*@Version : 1.0
*@Author : Andy
*@Website: http://www.21andy.com/
*@Update : 2008-06-07
*@Content : DB class for CodeIgniter
* ORIGINAL CODE FROM:
* Justin Vincent ([email protected])
* http://php.justinvincent.com
*/
define('OBJECT', 'OBJECT', true);
define('OBJECT_K', 'OBJECT_K', false);
define('ARRAY_A', 'ARRAY_A', false);
define('ARRAY_N', 'ARRAY_N', false);
class Db {
var $show_errors = false;
var $suppress_errors = false;
var $last_error = '';
var $num_queries = 0;
var $last_query;
var $col_info;
var $queries;
var $prefix = '';
var $ready = false;
var $charset;
var $collate;
var $savequeries = true;
function Db() {
include(APPPATH.'config/database'.EXT);
if ( ! isset($db) OR count($db) == 0)
{
show_error('No database connection settings were found in the database config file.');
}
if ( ! isset($active_group) OR ! isset($db[$active_group]))
{
show_error('You have specified an invalid database connection group.');
}
$params = $db[$active_group];
$this->dbuser = $params['username'];
$this->dbpassword = $params['password'];
$this->dbname = $params['database'];
$this->dbhost = $params['hostname'];
$this->charset = $params['char_set'];
$this->collate = $params['dbcollat'];
register_shutdown_function(array(&$this, "__destruct"));
if ( defined('DEBUG') and DEBUG == true )
$this->show_errors();
if ( defined('DB_CHARSET') )
$this->charset = DB_CHARSET;
if ( defined('DB_COLLATE') )
$this->collate = DB_COLLATE;
$this->dbh = @mysql_connect($this->dbhost, $this->dbuser, $this->dbpassword, true);
if (!$this->dbh) {
$this->bail("can't connect to db");
return;
}
$this->ready = true;
if( !empty($this->charset) )
mysql_query("SET character_set_connection={$this->charset}, character_set_results={$this->charset}, character_set_client=binary");
if($this->version() > '5.0.1')
mysql_query("SET sql_mode=''");
$this->select($this->dbname);
}
function __destruct() {
return true;
}
function version() {
return mysql_get_server_info();
}
function select($db) {
if ([email protected]mysql_select_db($db, $this->dbh)) {
$this->ready = false;
$this->bail("select db error $db");
return;
}
}
function save_query($enable = false) {
$this->savequeries = $enable;
}
function escape($string) {
return addslashes( $string );
}
function escape_by_ref(&$s) {
$s = $this->escape($s);
}
function prepare($args=NULL) {
if ( NULL === $args )
return;
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
$query = str_replace('"%s"', '%s', $query); // doublequote unquoting
$query = str_replace('%s', "'%s'", $query); // quote the strings
array_walk($args, array(&$this, 'escape_by_ref'));
return @vsprintf($query, $args);
}
function print_error($str = '') {
if (!$str) $str = mysql_error($this->dbh);
if ( $this->suppress_errors )
return false;
$error_str = "Database error $str for query $this->last_query";
if ( $caller = $this->get_caller() )
$error_str .= " made by $caller";
$log_error = true;
if ( ! function_exists('error_log') )
$log_error = false;
$log_file = @ini_get('error_log');
if ( !empty($log_file) && ('syslog' != $log_file) && !is_writable($log_file) )
$log_error = false;
if ( $log_error )
@error_log($error_str, 0);
// Is error output turned on or not..
if ( !$this->show_errors )
return false;
$str = htmlspecialchars($str, ENT_QUOTES);
$query = htmlspecialchars($this->last_query, ENT_QUOTES);
// If there is an error then take note of it
print "<div id='error'>
<p class='wpdberror'><strong>Database error:</strong> [$str]<br />
<code>$query</code></p>
</div>";
}
function show_errors( $show = true ) {
$errors = $this->show_errors;
$this->show_errors = $show;
return $errors;
}
function hide_errors() {
$show = $this->show_errors;
$this->show_errors = false;
return $show;
}
function suppress_errors( $suppress = true ) {
$errors = $this->suppress_errors;
$this->suppress_errors = $suppress;
return $errors;
}
function flush() {
$this->last_result = array();
$this->col_info = null;
$this->last_query = null;
}
function query($query) {
if ( ! $this->ready )
return false;
$return_val = 0;
$this->flush();
$this->func_call = "\$db->query(\"$query\")";
$this->last_query = $query;
if ($this->savequeries)
$this->timer_start();
$this->result = @mysql_query($query, $this->dbh);
++$this->num_queries;
if ($this->savequeries)
$this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
if ( $this->last_error = mysql_error($this->dbh) ) {
$this->print_error();
return false;
}
if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
$this->rows_affected = mysql_affected_rows($this->dbh);
if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
$this->insert_id = mysql_insert_id($this->dbh);
}
$return_val = $this->rows_affected;
} else {
$i = 0;
while ($i < @mysql_num_fields($this->result)) {
$this->col_info[$i] = @mysql_fetch_field($this->result);
$i++;
}
$num_rows = 0;
while ( $row = @mysql_fetch_object($this->result) ) {
$this->last_result[$num_rows] = $row;
$num_rows++;
}
@mysql_free_result($this->result);
$this->num_rows = $num_rows;
$return_val = $this->num_rows;
}
return $return_val;
}
function add_magic_quotes( $array ) {
foreach ( $array as $k => $v ) {
if ( is_array( $v ) ) {
$array[$k] = $this->add_magic_quotes( $v );
} else {
$array[$k] = $this->escape( $v );
}
}
return $array;
}
function insert($table, $data) {
$data = $this->add_magic_quotes($data);
$fields = array_keys($data);
return $this->query("INSERT INTO $table (`" . implode('`,`',$fields) . "`) VALUES ('".implode("','",$data)."')");
}
function update($table, $data, $where){
$data = $this->add_magic_quotes($data);
$bits = $wheres = array();
foreach ( array_keys($data) as $k )
$bits[] = "`$k` = '$data[$k]'";
if ( is_array( $where ) )
foreach ( $where as $c => $v )
$wheres[] = "$c = '" . $this->escape( $v ) . "'";
else
return false;
return $this->query( "UPDATE $table SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ) . ' LIMIT 1' );
}
function get_var($query=null, $x = 0, $y = 0) {
$this->func_call = "\$db->get_var(\"$query\",$x,$y)";
if ( $query )
$this->query($query);
if ( !empty( $this->last_result[$y] ) ) {
$values = array_values(get_object_vars($this->last_result[$y]));
}
return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
}
function get_row($query = null, $output = OBJECT, $y = 0) {
$this->func_call = "\$db->get_row(\"$query\",$output,$y)";
if ( $query )
$this->query($query);
else
return null;
if ( !isset($this->last_result[$y]) )
return null;
if ( $output == OBJECT ) {
return $this->last_result[$y] ? $this->last_result[$y] : null;
} elseif ( $output == ARRAY_A ) {
return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
} elseif ( $output == ARRAY_N ) {
return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
} else {
$this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
}
}
function get_col($query = null , $x = 0) {
if ( $query )
$this->query($query);
$new_array = array();
for ( $i=0; $i < count($this->last_result); $i++ ) {
$new_array[$i] = $this->get_var(null, $x, $i);
}
return $new_array;
}
function get_results($query = null, $output = OBJECT) {
$this->func_call = "\$db->get_results(\"$query\", $output)";
if ( $query )
$this->query($query);
else
return null;
if ( $output == OBJECT ) {
return $this->last_result;
} elseif ( $output == OBJECT_K ) {
foreach ( $this->last_result as $row ) {
$key = array_shift( get_object_vars( $row ) );
if ( !isset( $new_array[ $key ] ) )
$new_array[ $key ] = $row;
}
return $new_array;
} elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
if ( $this->last_result ) {
$i = 0;
foreach( $this->last_result as $row ) {
if ( $output == ARRAY_N ) {
$new_array[$i] = array_values( get_object_vars( $row ) );
} else {
$new_array[$i] = get_object_vars( $row );
}
++$i;
}
return $new_array;
}
}
}
function get_col_info($info_type = 'name', $col_offset = -1) {
if ( $this->col_info ) {
if ( $col_offset == -1 ) {
$i = 0;
foreach($this->col_info as $col ) {
$new_array[$i] = $col->{$info_type};
$i++;
}
return $new_array;
} else {
return $this->col_info[$col_offset]->{$info_type};
}
}
}
function timer_start() {
$mtime = microtime();
$mtime = explode(' ', $mtime);
$this->time_start = $mtime[1] + $mtime[0];
return true;
}
function timer_stop() {
$mtime = microtime();
$mtime = explode(' ', $mtime);
$time_end = $mtime[1] + $mtime[0];
$time_total = $time_end - $this->time_start;
return $time_total;
}
function bail($message) { // Just wraps errors in a nice header and footer
if ( !$this->show_errors ) {
$this->error = $message;
return false;
}
die($message);
}
function supports_collation() {
return ( version_compare(mysql_get_server_info($this->dbh), '4.1.0', '>=') );
}
function get_caller() {
if ( !is_callable('debug_backtrace') )
return '';
$bt = debug_backtrace();
$caller = '';
foreach ( $bt as $trace ) {
if ( @$trace['class'] == __CLASS__ )
continue;
elseif ( strtolower(@$trace['function']) == 'call_user_func_array' )
continue;
$caller = $trace['function'];
break;
}
return $caller;
}
}
Incoming search terms:
- You have specified an invalid database connection group
- CI You have specified an invalid database connection group
- codeigniter you have specified an invalid database connection group
- codeigniter db
- No database connection settings were found in the database config file
- you have specified an invalid database connection group codeigniter
- ci框架 You have specified an invalid database connection group
- db class for php
- You have specified an invalid database connection group (entries) in your config/database php file
- You have specified an invalid database connection group (hanrong) in your config/database php file
Tags: CodeIgniter, class