十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
我自己封裝的一個
成都網(wǎng)絡公司-成都網(wǎng)站建設公司成都創(chuàng)新互聯(lián)十載經(jīng)驗成就非凡,專業(yè)從事成都網(wǎng)站制作、成都網(wǎng)站設計,成都網(wǎng)頁設計,成都網(wǎng)頁制作,軟文推廣,廣告投放平臺等。十載來已成功提供全面的成都網(wǎng)站建設方案,打造行業(yè)特色的成都網(wǎng)站建設案例,建站熱線:18980820575,我們期待您的來電!
?php
class AppConfig{
public static $dbParam = array(
'dbHost' = 'localhost',
'dbUser' = 'root',
'dbPassword' ='',
'dbName' = '數(shù)據(jù)庫名',
'dbCharset' = 'utf8',
'dbPort' = 3306,
'dbPrefix' = 'test_',
'dbPconnect' = 0,
'dbDebug' = true,
);
}
class Model {
private $version = ''; //mysql版本
private $config = array(); //數(shù)據(jù)庫配置數(shù)組
private $class; //當前類名
public $tablepre = 'ts_'; //表前綴
public $db = ''; //庫名
public $table = ''; //表名
private static $link; //數(shù)據(jù)庫鏈接句柄
private $data = array(); //中間數(shù)據(jù)容器
private $condition = ''; //查詢條件
private $fields = array(); //字段信息
private $sql = array(); //sql集合,調(diào)試用
public $primaryKey = 'id'; //表主鍵
//構(gòu)造函數(shù)初始化
public function __construct($dbParam = array()) {
$this-config = (is_array($dbParam) !empty($dbParam)) ? $dbParam : AppConfig::$dbParam;
$this-connect();
$this-init();
}
//鏈接數(shù)據(jù)庫
private function connect() {
if($this-config['dbPconnect']) {
self::$link = @mysql_pconnect($this-config['dbHost'], $this-config['dbUser'], $this-config['dbPassword']);
}else{
self::$link = @mysql_connect($this-config['dbHost'], $this-config['dbUser'], $this-config['dbPassword'], true);
}
mysql_errno(self::$link) != 0 $this-errdie('Could not connect Mysql: ');
$this-db= !empty($this-db) ? $this-db : $this-config['dbName'];
$serverinfo = $this-version();
if ($serverinfo '4.1' $this-config['dbCharset']) {
mysql_query("SET character_set_connection=".$this-config['dbCharset'].",character_set_results=".$this-config['dbCharset'].",character_set_client=binary", self::$link);
}
if ($serverinfo '5.0') {
mysql_query("SET sql_mode=''", self::$link);
}
@mysql_select_db($this-db, self::$link) or $this-errdie('Cannot use database');
return self::$link;
}
//表基本信息初始化
protected function init() {
$this-class = get_class($this);
$this-table = !empty($this-table) ? $this-table : strtolower($this-class);
$this-table = $this-tablepre . $this-table;
return $this;
}
//設置屬性值
public function __set($name, $value) {
//exit($value);
$this-data['fields'][$name] = $value;
}
//獲取屬性值
public function __get($name) {
if(isset($this-data['fields'][$name])) {
return($this-data['fields'][$name]);
}else {
return NULL;
}
}
//字段信息處理
private function implodefields($data) {
if (!is_array($data)) {
$data = array();
}
$this-fields = !empty($this-data['fields']) ? array_merge($this-data['fields'], $data) : $data;
foreach($this-fields as $key = $value) {
$fieldsNameValueStr[] = "`$key`='$value'";
$fieldsNameStr[] = "`$key`";
$fieldsValueStr[] = "'$value'";
}
return array($fieldsNameValueStr, $fieldsNameStr, $fieldsValueStr);
}
//條件判斷組裝
private function condition($where = NULL) {
if (is_numeric($where)) {
$where = "WHERE `{$this-primaryKey}`='{$where}' LIMIT 1";
}elseif (is_array($where)){
$where = "WHERE `{$this-primaryKey}` in (".implode(',',$where).")";
}elseif(!empty($this-data['condition'])){
//'預留WHERE', 'order', 'group', 'limit' …………等條件關鍵詞處理接口
$where = $where ? "WHERE {$where}" : "WHERE 1";
isset($this-data['condition']['where']) $where .= ' AND '.$this-data['condition']['where'];
isset($this-data['condition']['group']) $where .= ' GROUP BY '.$this-data['condition']['group'];
isset($this-data['condition']['order']) $where .= ' ORDER BY '.$this-data['condition']['order'];
isset($this-data['condition']['limit']) $where .= ' LIMIT '.$this-data['condition']['limit'];
}else{
$where = "WHERE {$where}";
}
$this-condition = $where;
return $this;
}
//插入數(shù)據(jù)
public function insert($data = array(), $replace = false) {
$fields = $this-implodefields($data);
$insert = $replace ? 'REPLACE' : 'INSERT';
$sql = "{$insert} INTO `{$this-db}`.`{$this-table}` (".implode(', ',$fields[1]).") values (".implode(', ',$fields[2]).")";
$this-query($sql);
return $this-getInsertId();
}
//更新數(shù)據(jù)
public function update($data = array() ,$where = '') {
$numargs = func_num_args();
if ($numargs == 1) {
$where = $data;
$data = array();
}
$fields = $this-implodefields($data);
$this-condition($where);
$sql = "UPDATE `{$this-db}`.`{$this-table}` SET ".implode(', ',$fields[0])." {$this-condition}";
$this-query($sql);
return $this-getAffectedRows();
}
//刪除數(shù)據(jù)
public function delete($where = NULL) {
if(!is_array($where) strtolower(substr(trim($where), 0, 6)) == 'delete'){
$sql = $where;
}else{
$this-condition($where);
$sql = "DELETE FROM `{$this-db}`.`{$this-table}` {$this-condition}";
}
$this-query($sql);
return $this-getAffectedRows();
}
//查詢數(shù)據(jù)
public function select($where = NULL, $fields = '*') {
if(!is_array($where) strtolower(substr(trim($where), 0, 6)) == 'select'){
$sql = $where;
}else{
$this-condition($where);
$sql = "SELECT {$fields} FROM `{$this-db}`.`{$this-table}` {$this-condition}";
}
return $this-fetch($this-query($sql));
}
//查詢一條數(shù)據(jù)
public function getOne($where, $fields = '*') {
$data = $this-select($where, $fields = '*');
if($data) {
return $data[0];
}
return array();
}
//查詢多條數(shù)據(jù)
public function getAll($where, $fields = '*') {
$data = $this-select($where, $fields = '*');
return $data;
}
//結(jié)果數(shù)量
public function getCount($where = '', $fields = '*') {
$this-condition($where);
$sql = "SELECT count({$fields}) as count FROM `{$this-db}`.`{$this-table}` {$this-condition}";
$data = $this-query($sql);
if($data){
return @mysql_result($data,0);
}
return 0;
}
//執(zhí)行sql語句(flag為0返回mysql_query查詢后的結(jié)果,為1返回lastid,其他返回影響行數(shù),默認為2返回影響行數(shù))
public function query($sql, $flag = '0', $type = '') {
if ($this-config['dbDebug']) {
$startime = $this-microtime_float();
}
//查詢
if ($type == 'UNBUFFERED' function_exists('mysql_unbuffered_query')) {
$result = @mysql_unbuffered_query($sql, self::$link);
} else {
//exit($sql);
$result = @mysql_query($sql, self::$link);
}
//重試
if (in_array(mysql_errno(self::$link), array(2006,2013)) empty($result) $this-config['dbPconnect']==0 !defined('RETRY')) {
define('RETRY',true); @mysql_close(self::$link); sleep(2);
$this-connect();
$result = $this-query($sql);
}
if ($result === false) {
$this-errdie($sql);
}
if ($this-config['dbDebug']) {
$endtime = $this-microtime_float();
$this-sql[] = array($sql,$endtime-$startime);
}
//清空操作數(shù)據(jù)
$this-data = array();
return $flag == '0' ? $result : ($flag == '1' ? $this-getInsertId() : $this-getAffectedRows());
}
//返回結(jié)果$onlyone為true返回一條否則返回所有,$type有MYSQL_ASSOC,MYSQL_NUM,MYSQL_BOTH
public function fetch($result, $onlyone = false, $type = MYSQL_ASSOC) {
if($result){
if ($onlyone) {
$row = @mysql_fetch_array($result, $type);
return $row;
}else{
$rowsRs = array();
while($row=@mysql_fetch_array($result, $type)) {
$rowsRs[] = $row;
}
return $rowsRs;
}
}
return array();
}
//可以運行SELECT,SHOW,EXPLAIN 或 DESCRIBE 等返回一個資源標識符的語句得到返回結(jié)果數(shù)組
public function show($sql, $onlyone = false) {
return $this-fetch($this-query($sql), $onlyone);
}
// 使用call函數(shù)處理同類型函數(shù)
private function __call($name, $arguments) {
$callArr = array('on', 'where', 'order', 'between', 'group', 'limit');
if (in_array($name, $callArr)) {
$this-data['condition'][$name] = $arguments[0];
}else{
$this-errdie("function error: function {$name} is not in ($this-class) class exist");
}
return $this;
}
//返回最后一次插入ID
public function getInsertId() {
return @mysql_insert_id(self::$link);
}
//返回受影響行數(shù)
public function getAffectedRows() {
return @mysql_affected_rows(self::$link);
}
//獲取錯誤信息
private function error() {
return ((self::$link) ? @mysql_error(self::$link) : @mysql_error());
}
//獲取錯誤信息ID
private function errno() {
return ((self::$link) ? @mysql_errno(self::$link) : @mysql_errno());
}
//獲取版本信息
function version() {
if(empty($this-version)) {
$this-version = mysql_get_server_info(self::$link);
}
return $this-version;
}
//打印錯誤信息
private function errdie($sql = '') {
if ($this-config['dbDebug']) {
die('/BRBMySQL ERROR/B/BR
SQL:'.$sql.'/BR
ERRNO:'.$this-errno().'/BR
ERROR:'.$this-error().'/BR');
}
die('DB ERROR?。?!');
}
//獲取時間微妙數(shù)
private function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
//析構(gòu)函數(shù)
public function __destruct() {
echo 'hr';
$this-config['dbDebug'] print_r($this-sql);
//unset($this-result);
//unset($this-condition);
//unset($this-data);
}
}
class user extends Model {
//public $db = 'qsf_mvc';
//public $table = 'user';
public $primaryKey = 'uid';
}
$userObj = new user();
//---------------------------------------插入數(shù)據(jù)方法一-----------------------------------------
//模擬ActiveRecord模式 插入數(shù)據(jù)
$userObj-username = 'hoho';
$userObj-passwd = '1478522';
$userObj-email = 'qsf.z11@163.com';
$userObj-sex = 1;
$userObj-desc = '清潔工';
$insetId = $userObj-insert();
if ($insetId 0) {
echo "插入ID為:{$insetId}BR";
}
//---------------------------------------插入數(shù)據(jù)方法二-----------------------------------------
//直接數(shù)組做參數(shù)插入數(shù)據(jù)
$userArr = array(
'username' = 'hoho',
'passwd' = '1478522',
'email' = 'qsf.z2121ia@163.com',
'sex' = '1',
'desc' = '廚師',
);
$insetId = $userObj-insert($userArr);
if ($insetId 0) {
echo "插入ID為:{$insetId}BR";
}
//---------------------------------------更新數(shù)據(jù)方法一----------------------------------------
$userObj-username = 'h111oho';
$userObj-passwd = '1478511122';
$userObj-email = 'qsf111ia@163.com';
$userObj-sex = 1;
$userObj-desc = '清潔工';
$affectedRows1 = $userObj-update(89);
if ($affectedRows1 0) {
echo "影響行數(shù)為:{$affectedRows1}BR";
}
//---------------------------------------更新數(shù)據(jù)方法二----------------------------------------
//更新記錄(傳遞參數(shù)的方式和insert操作一樣)
$userArr = array(
'username' = 'hohoho',
'passwd' = '1474rr4448522',
'email' = 'qsf.rrza@165.com',
'sex' = '0',
'desc' = '廚師qq',
);
$affectedRows = $userObj-update($userArr, $insetId);
if ($affectedRows 0) {
echo "影響行數(shù)為:{$affectedRows}BR";
}
//----------------------------------------查詢數(shù)據(jù)----------------------------------------------
$userRs0 = $userObj-select(8); //單個主鍵值
//print_r($userRs0);
$userRs1 = $userObj-select(array(1,5,8)); //多個主鍵值的數(shù)組
//print_r($userRs1);
$userRs2 = $userObj-select('select count(*) as count from user where uid 20'); //直接完整sql語句
//print_r($userRs2);
$userRs3 = $userObj-select("`uid` 0"); //where條件
//print_r($userRs3);
$userRs4 = $userObj-getOne("`uid` 0"); //獲取單條記錄
//print_r($userRs4);
$usersRs5 = $userObj-getAll("`uid` 0"); ////獲取所有記錄
//print_r($usersRs5);
$usersRs6 = $userObj-limit('0,10')-where('uid 100')-order('uid DESC')-group('username')-select();
//print_r($usersRs6);
//----------------------------------------刪除數(shù)據(jù)-----------------------------------------------
//刪除操作傳遞參數(shù)的方式和select操作一樣
$userObj-delete(60); //單個主鍵值
$userObj-delete(array(1,5,8)); //多個主鍵值的數(shù)組
$userObj-delete('delete from user where uid 100'); //直接完整sql語句
$userObj-delete("`uid` 100"); //where條件
$userObj-limit('5')-where('uid 80')-delete();
//----------------------------------------特殊查詢-----------------------------------------------
$userShowRs = $userObj-show('show create table user', true); //獲取特殊查詢的結(jié)果,第二個參數(shù)代表返回一條結(jié)果還是所有的結(jié)果
?php
class db{
private $db;
const MYSQL_OPT_READ_TIMEOUT = 11;
const MYSQL_OPT_WRITE_TIMEOUT = 12;
private $tbl_name;
private $where;
private $sort;
private $fields;
private $limit;
public static $_instance = null;
function __construct(){
$cfg = loadConfig('db');
$db = mysqli_init();
$db-options(self::MYSQL_OPT_READ_TIMEOUT, 3);
$db-options(self::MYSQL_OPT_WRITE_TIMEOUT, 1);
@$db-real_connect($cfg['host'],$cfg['user'],$cfg['pwd'],$cfg['db']);
if ($db-connect_error) {
$this-crash($db-errno,$db-error);
}
$db-set_charset("utf8");
$this-db = $db;
//echo $this-db-stat;
}
public static function getInstance(){
if(!(self::$_instance instanceof self)){
self::$_instance = new self();
}
return self::$_instance;
}
private function __clone() {} //覆蓋__clone()方法,禁止克隆
public function find($conditions = null){
if($conditions) $this-where($conditions);
return $this-getArray($this-buildSql(),1);
}
public function findAll($conditions = null){
if($conditions) $this-where($conditions);
return $this-getArray($this-buildSql());
}
//表
public function t($table){ $this-tbl_name = $table; return $this;}
//條件
public function where($conditions){
$where = '';
if(is_array($conditions)){
$join = array();
foreach( $conditions as $key = $condition ){
$condition = $this-db-real_escape_string($condition);
$join[] = "`{$key}` = '{$condition}'";
}
$where = "WHERE ".join(" AND ",$join);
}else{
if(null != $conditions) $where = "WHERE ".$conditions;
}
$this-where = $where;
return $this;
}
//排序
public function sort($sort){
if(null != $sort) $sort = "ORDER BY {$sort}";
$this-sort = $sort;
return $this;
}
//字段
public function fields($fields){ $this-fields = $fields; return $this; }
public function limit($limit){$this-limit = $limit; return $this;}
private function buildSql(){
$this-fields = empty($this-fields) ? "*" : $this-fields;
$sql = "SELECT {$this-fields} FROM {$this-tbl_name} {$this-where} {$this-sort}";
accessLog('db_access',$sql);
if(null != $this-limit)$sql .= " limit {$this-limit}";
return $sql;
}
/**
* 返回查詢數(shù)據(jù)
* @param $sql
* @param bool $hasOne
* @return array|bool|mixed
*/
private function getArray($sql,$hasOne = false){
if($this-db-real_query($sql) ){
if ($result = $this-db-use_result()) {
$row = array();
if($hasOne){
$row = $result-fetch_assoc();
}else{
while($d = $result-fetch_assoc()) $row[] = $d;
}
$result-close();
$this-fields = "*";
return $row;
}else{
return false;
}
}else{
if($this-db-error){
$this-crash($this-db-errno,$this-db-error,$sql);
}
}
}
public function findSql($sql,$hasOne = false){
accessLog('db_access',$sql);
if($this-db-real_query($sql) ){
if ($result = $this-db-use_result()) {
$row = array();
if($hasOne){
$row = $result-fetch_assoc();
}else{
while($d = $result-fetch_assoc()) $row[] = $d;
}
$result-close();
$this-fields = "*";
return $row;
}else{
return false;
}
}else{
if($this-db-error){
$this-crash($this-db-errno,$this-db-error,$sql);
}
}
}
public function create($row){
if(!is_array($row))return FALSE;
$row = $this-prepera_format($row);
if(empty($row))return FALSE;
foreach($row as $key = $value){
$cols[] = '`'.$key.'`';
$vals[] = "'".$this-db-real_escape_string($value)."'";
}
$col = implode(',', $cols);
$val = implode(',', $vals);
$sql = "INSERT INTO `{$this-tbl_name}` ({$col}) VALUES ({$val})";
accessLog('db_access',$sql);
if( FALSE != $this-db-query($sql) ){ // 獲取當前新增的ID
if($this-db-insert_id){
return $this-db-insert_id;
}
if($this-db-affected_rows){
return true;
}
}
return FALSE;
}
//直接執(zhí)行sql
public function runSql($sql){
accessLog('db_access',$sql);
if( FALSE != $this-db-query($sql) ){ // 獲取當前新增的ID
return true;
}else{
return false;
}
}
public function update($row){
$where = "";
$row = $this-prepera_format($row);
if(empty($row))return FALSE;
foreach($row as $key = $value){
$value = $this-db-real_escape_string($value);
$vals[] = "`{$key}` = '{$value}'";
}
$values = join(", ",$vals);
$sql = "UPDATE {$this-tbl_name} SET {$values} {$this-where}";
accessLog('db_access',$sql);
if( FALSE != $this-db-query($sql) ){ // 獲取當前新增的ID
if( $this-db-affected_rows){
return true;
}
}
return false;
}
function delete(){
$sql = "DELETE FROM {$this-tbl_name} {$this-where}";
if( FALSE != $this-db-query($sql) ){ // 獲取當前新增的ID
if( $this-db-affected_rows){
return true;
}
}
return FALSE;
}
private function prepera_format($rows){
$columns = $this-getArray("DESCRIBE {$this-tbl_name}");
$newcol = array();
foreach( $columns as $col ){
$newcol[$col['Field']] = $col['Field'];
}
return array_intersect_key($rows,$newcol);
}
//崩潰信息
private function crash($number,$message,$sql=''){
$msg = 'Db Error '.$number.':'.$message ;
if(empty($sql)){
echo t('db_crash');
}else{
$msg .= " SQL:".$sql;
echo t('db_query_err');
}
accessLog('db_error',$msg);
exit;
}
}
類文件mysql.class.php:
?php
class?Mysql{
//數(shù)據(jù)庫連接返回值
private?$conn;
/**
*?[構(gòu)造函數(shù),返回值給$conn]
*?@param?[string]?$hostname?[主機名]
*?@param?[string]?$username[用戶名]
*?@param?[string]?$password[密碼]
*?@param?[string]?$dbname[數(shù)據(jù)庫名]
*?@param?[string]?$charset[字符集]
*?@return?[null]
*/
function?__construct($hostname,$username,$password,$dbname,$charset='utf8'){
$config?=?@mysql_connect($hostname,$username,$password);
if(!$config){
echo?'連接失敗,請聯(lián)系管理員';
exit;
}
$this-conn?=?$config;
$res?=?mysql_select_db($dbname);
if(!$res){
echo?'連接失敗,請聯(lián)系管理員';
exit;
}
mysql_set_charset($charset);
}
function?__destruct(){
mysql_close();
}
/**
*?[getAll?獲取所有信息]
*?@param?[string]?$sql?[sql語句]
*?@return?[array]?[返回二維數(shù)組]
*/
function?getAll($sql){
$result?=?mysql_query($sql,$this-conn);
$data?=?array();
if($result??mysql_num_rows($result)0){
while($row?=?mysql_fetch_assoc($result)){
$data[]?=?$row;
}
}
return?$data;
}
/**
*?[getOne?獲取單條數(shù)據(jù)]
*?@param?[string]?$sql?[sql語句]
*?@return?[array]?[返回一維數(shù)組]
*/
function?getOne($sql){
$result?=?mysql_query($sql,$this-conn);
$data?=?array();
if($result??mysql_num_rows($result)0){
$data?=?mysql_fetch_assoc($result);
}
return?$data;
}
/**
*?[getOne?獲取單條數(shù)據(jù)]
*?@param?[string]?$table?[表名]
*?@param?[string]?$data?[由字段名當鍵,屬性當鍵值的一維數(shù)組]
*?@return?[type]?[返回false或者插入數(shù)據(jù)的id]
*/
function?insert($table,$data){
$str?=?'';
$str?.="INSERT?INTO?`$table`?";
$str?.="(`".implode("`,`",array_keys($data))."`)?";
$str?.="?VALUES?";
$str?.=?"('".implode("','",$data)."')";
$res?=?mysql_query($str,$this-conn);
if($res??mysql_affected_rows()0){
return?mysql_insert_id();
}else{
return?false;
}
}
/**
*?[update?更新數(shù)據(jù)庫]
*?@param?[string]?$table?[表名]
*?@param?[array]?$data?[更新的數(shù)據(jù),由字段名當鍵,屬性當鍵值的一維數(shù)組]
*?@param?[string]?$where?[條件,‘字段名’=‘字段屬性’]
*?@return?[type]?[更新成功返回影響的行數(shù),更新失敗返回false]
*/
function?update($table,$data,$where){
$sql?=?'UPDATE?'.$table.'?SET?';
foreach($data?as?$key?=?$value){
$sql?.=?"`{$key}`='{$value}',";
}
$sql?=?rtrim($sql,',');
$sql?.=?"?WHERE?$where";
$res?=?mysql_query($sql,$this-conn);
if($res??mysql_affected_rows()){
return?mysql_affected_rows();
}else{
return?false;
}
}
/**
*?[delete?刪除數(shù)據(jù)]
*?@param?[string]?$table?[表名]
*?@param?[string]?$where?[條件,‘字段名’=‘字段屬性’]
*?@return?[type]?[成功返回影響的行數(shù),失敗返回false]
*/
function?del($table,$where){
$sql?=?"DELETE?FROM?`{$table}`?WHERE?{$where}";
$res?=?mysql_query($sql,$this-conn);
if($res??mysql_affected_rows()){
return?mysql_affected_rows();
}else{
return?false;
}
}
}
?
使用案例:
?php
//包含數(shù)據(jù)庫操作類文件
include?'mysql.class.php';
//設置傳入?yún)?shù)
$hostname='localhost';
$username='root';
$password='123456';
$dbname='aisi';
$charset?=?'utf8';
//實例化對象
$db?=?new?Mysql($hostname,$username,$password,$dbname);
//獲取一條數(shù)據(jù)
$sql?=?"SELECT?count(as_article_id)?as?count?FROM?as_article?where?as_article_type_id=1";
$count?=?$db-getOne($sql);
//獲取多條數(shù)據(jù)
$sql?=?"SELECT?*?FROM?as_article?where?as_article_type_id=1?order?by?as_article_addtime?desc?limit?$start,$limit";
$service?=?$db-getAll($sql);
//插入數(shù)據(jù)
$arr?=?array(
'as_article_title'='數(shù)據(jù)庫操作類',
'as_article_author'='rex',
);
$res?=?$db-insert('as_article',$arr);
//更新數(shù)據(jù)
$arr?=?array(
'as_article_title'='實例化對象',
'as_article_author'='Lee',
);
$where?=?"as_article_id=1";
$res?=?$db-update('as_article',$arr,$where);
//刪除數(shù)據(jù)
$where?=?"as_article_id=1";
$res?=?$db-del('as_article',$where);
?
?php
class MySQL{
private $host; //服務器地址
private $name; //登錄賬號
private $pwd; //登錄密碼
private $dBase; //數(shù)據(jù)庫名稱
private $conn; //數(shù)據(jù)庫鏈接資源
private $result; //結(jié)果集
private $msg; //返回結(jié)果
private $fields; //返回字段
private $fieldsNum; //返回字段數(shù)
private $rowsNum; //返回結(jié)果數(shù)
private $rowsRst; //返回單條記錄的字段數(shù)組
private $filesArray = array(); //返回字段數(shù)組
private $rowsArray = array(); //返回結(jié)果數(shù)組
private $charset='utf8'; //設置操作的字符集
private $query_count=0; //查詢結(jié)果次數(shù)
static private $_instance; //存儲對象
//初始化類
private function __construct($host='',$name='',$pwd='',$dBase=''){
if($host != '') $this-host = $host;
if($name != '') $this-name = $name;
if($pwd != '') $this-pwd = $pwd;
if($dBase != '') $this-dBase = $dBase;
$this-init_conn();
}
//防止被克隆
private function __clone(){}
public static function getInstance($host='',$name='',$pwd='',$dBase=''){
if(FALSE == (self::$_instance instanceof self)){
self::$_instance = new self($host,$name,$pwd,$dBase);
}
return self::$_instance;
}
public function __set($name,$value){
$this-$name=$value;
}
public function __get($name){
return $this-$name;
}
//鏈接數(shù)據(jù)庫
function init_conn(){
$this-conn=@mysql_connect($this-host,$this-name,$this-pwd) or die('connect db fail !');
@mysql_select_db($this-dBase,$this-conn) or die('select db fail !');
mysql_query("set names ".$this-charset);
}
//查詢結(jié)果
function mysql_query_rst($sql){
if($this-conn == '') $this-init_conn();
$this-result = @mysql_query($sql,$this-conn);
$this-query_count++;
}
//取得字段數(shù)
function getFieldsNum($sql){
$this-mysql_query_rst($sql);
$this-fieldsNum = @mysql_num_fields($this-result);
}
//取得查詢結(jié)果數(shù)
function getRowsNum($sql){
$this-mysql_query_rst($sql);
if(mysql_errno() == 0){
return @mysql_num_rows($this-result);
}else{
return '';
}
}
//取得記錄數(shù)組(單條記錄)
function getRowsRst($sql,$type=MYSQL_BOTH){
$this-mysql_query_rst($sql);
if(empty($this-result)) return '';
if(mysql_error() == 0){
$this-rowsRst = mysql_fetch_array($this-result,$type);
return $this-rowsRst;
}else{
return '';
}
}
//取得記錄數(shù)組(多條記錄)
function getRowsArray($sql,$type=MYSQL_BOTH){
!empty($this-rowsArray) ? $this-rowsArray=array() : '';
$this-mysql_query_rst($sql);
if(mysql_errno() == 0){
while($row = mysql_fetch_array($this-result,$type)) {
$this-rowsArray[] = $row;
}
return $this-rowsArray;
}else{
return '';
}
}
//更新、刪除、添加記錄數(shù)
function uidRst($sql){
if($this-conn == ''){
$this-init_conn();
}
@mysql_query($sql);
$this-rowsNum = @mysql_affected_rows();
if(mysql_errno() == 0){
return $this-rowsNum;
}else{
return '';
}
}
//返回最近插入的一條數(shù)據(jù)庫的id值
function returnRstId($sql){
if($this-conn == ''){
$this-init_conn();
}
@mysql_query($sql);
if(mysql_errno() == 0){
return mysql_insert_id();
}else{
return '';
}
}
//獲取對應的字段值
function getFields($sql,$fields){
$this-mysql_query_rst($sql);
if(mysql_errno() == 0){
if(mysql_num_rows($this-result) 0){
$tmpfld = @mysql_fetch_row($this-result);
$this-fields = $tmpfld[$fields];
}
return $this-fields;
}else{
return '';
}
}
//錯誤信息
function msg_error(){
if(mysql_errno() != 0) {
$this-msg = mysql_error();
}
return $this-msg;
}
//釋放結(jié)果集
function close_rst(){
mysql_free_result($this-result);
$this-msg = '';
$this-fieldsNum = 0;
$this-rowsNum = 0;
$this-filesArray = '';
$this-rowsArray = '';
}
//關閉數(shù)據(jù)庫
function close_conn(){
$this-close_rst();
mysql_close($this-conn);
$this-conn = '';
}
//取得數(shù)據(jù)庫版本
function db_version() {
return mysql_get_server_info();
}
}
復制代碼
代碼如下:
?php
/*
MYSQL
數(shù)據(jù)庫訪問封裝類
MYSQL
數(shù)據(jù)訪問方式,php4支持以mysql_開頭的過程訪問方式,php5開始支持以mysqli_開頭的過程和mysqli面向?qū)ο?/p>
訪問方式,本封裝類以mysql_封裝
數(shù)據(jù)訪問的一般流程:
1,連接數(shù)據(jù)庫
mysql_connect
or
mysql_pconnect
2,選擇數(shù)據(jù)庫
mysql_select_db
3,執(zhí)行SQL查詢
mysql_query
4,處理返回的數(shù)據(jù)
mysql_fetch_array
mysql_num_rows
mysql_fetch_assoc
mysql_fetch_row
etc
*/
class
db_mysql
{
var
$querynum
=
;
//當前頁面進程查詢數(shù)據(jù)庫的次數(shù)
var
$dblink
;
//數(shù)據(jù)庫連接資源
//鏈接數(shù)據(jù)庫
function
connect($dbhost,$dbuser,$dbpw,$dbname='',$dbcharset='utf-8',$pconnect=0
,
$halt=true)
{
$func
=
empty($pconnect)
?
'mysql_connect'
:
'mysql_pconnect'
;
$this-dblink
=
@$func($dbhost,$dbuser,$dbpw)
;
if
($halt
!$this-dblink)
{
$this-halt("無法鏈接數(shù)據(jù)庫!");
}
//設置查詢字符集
mysql_query("SET
character_set_connection={$dbcharset},character_set_results={$dbcharset},character_set_client=binary",$this-dblink)
;
//選擇數(shù)據(jù)庫
$dbname
@mysql_select_db($dbname,$this-dblink)
;
}
//選擇數(shù)據(jù)庫
function
select_db($dbname)
{
return
mysql_select_db($dbname,$this-dblink);
}
//執(zhí)行SQL查詢
function
query($sql)
{
$this-querynum++
;
return
mysql_query($sql,$this-dblink)
;
}
//返回最近一次與連接句柄關聯(lián)的INSERT,UPDATE
或DELETE
查詢所影響的記錄行數(shù)
function
affected_rows()
{
return
mysql_affected_rows($this-dblink)
;
}
//取得結(jié)果集中行的數(shù)目,只對select查詢的結(jié)果集有效
function
num_rows($result)
{
return
mysql_num_rows($result)
;
}
//獲得單格的查詢結(jié)果
function
result($result,$row=0)
{
return
mysql_result($result,$row)
;
}
//取得上一步
INSERT
操作產(chǎn)生的
ID,只對表有AUTO_INCREMENT
ID的操作有效
function
insert_id()
{
return
($id
=
mysql_insert_id($this-dblink))
=
?
$id
:
$this-result($this-query("SELECT
last_insert_id()"),
0);
}
//從結(jié)果集提取當前行,以數(shù)字為key表示的關聯(lián)數(shù)組形式返回
function
fetch_row($result)
{
return
mysql_fetch_row($result)
;
}
//從結(jié)果集提取當前行,以字段名為key表示的關聯(lián)數(shù)組形式返回
function
fetch_assoc($result)
{
return
mysql_fetch_assoc($result);
}
//從結(jié)果集提取當前行,以字段名和數(shù)字為key表示的關聯(lián)數(shù)組形式返回
function
fetch_array($result)
{
return
mysql_fetch_array($result);
}
//關閉鏈接
function
close()
{
return
mysql_close($this-dblink)
;
}
//輸出簡單的錯誤html提示信息并終止程序
function
halt($msg)
{
$message
=
"html\nhead\n"
;
$message
.=
"meta
content='text/html;charset=gb2312'\n"
;
$message
.=
"/head\n"
;
$message
.=
"body\n"
;
$message
.=
"數(shù)據(jù)庫出錯:".htmlspecialchars($msg)."\n"
;
$message
.=
"/body\n"
;
$message
.=
"/html"
;
echo
$message
;
exit
;
}
}
?