Created
August 25, 2011 02:47
-
-
Save vivirenremoto/1169858 to your computer and use it in GitHub Desktop.
mysql php class
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{ | |
private $link; | |
function __construct( $config ){ | |
extract( $config ); | |
$this->link = mysqli_connect( $host, $user, $pass, $name, $port ) OR die( mysqli_connect_errno() ); | |
} | |
function __destruct(){ | |
@mysqli_close( $this->link ); | |
} | |
function clean( $str ){ | |
return mysqli_real_escape_string( $this->link, $str ); | |
} | |
function query( $query ){ | |
$res = mysqli_query( $this->link, $query ); | |
echo mysqli_error( $this->link ); | |
return $res; | |
} | |
function queryRow( $query ){ | |
$res = $this->query( $query ); | |
$row = $res->fetch_array( MYSQLI_ASSOC ); | |
return $row; | |
} | |
function queryOne( $query ){ | |
$res = $this->query( $query ); | |
$row = $res->fetch_array( MYSQLI_NUM ); | |
return $row[0]; | |
} | |
function queryAll( $query ){ | |
$rows = array(); | |
if( $this->link->multi_query( $query ) ){ | |
do{ | |
if( $result = $this->link->store_result() ){ | |
while( $row = $result->fetch_object() ){ | |
$rows[] = $row; | |
} | |
$result->free(); | |
} | |
}while( $this->link->next_result() ); | |
} | |
return $rows; | |
} | |
function getLastID(){ | |
return $this->queryOne( "SELECT LAST_INSERT_ID()" ); | |
} | |
} | |
// define db config | |
$db_config = array( | |
'name' => 'db_name', | |
'user' => 'db_username', | |
'pass' => 'db_password', | |
'host' => 'localhost', | |
'port' => 'port' | |
); | |
// initialize | |
$db = new DB( $db_config ); | |
// set utf8 encode, to avoid encoding issues | |
$db->query( "SET lc_time_names = 'es_ES', NAMES 'utf8'"); | |
// query example, multiple rows | |
$users = $db->queryAll( "SELECT * FROM users" ); | |
// query example, one row | |
$nick = 'miquelcamps'; | |
$user_info = $db->queryRow( sprintf( "SELECT * FROM users WHERE nick = '%s'", $db->clean( $nick ) ) ); | |
// query example, one result | |
$total_users = $db->queryOne( "SELECT COUNT(*) FROM users" ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment