已掉线,重新登录

首页 > 绿虎论坛 > 历史版块 > 编程 > PHP > 教程

标题: 单例模式 Mysql 类

作者: @Ta

时间: 2014-12-12

点击: 1792

<?php
class Mysql{
private static $db; //该类的对象
private $con; // Mysql链接
private $config; // Mysql配置信息
//Mysql的链接
/*
* 构造方法
* 链接数据库
* 设置字符集
* 选择数据库
*/
final private function __construct(){
//链接数据库
$this->config=$_SESSION['config'];
$this->con=mysql_connect($this->config['host'],$this->config['user'],$this->config['password']);
if(is_resource($this->con)){
$this->charset();
if($this->config['dbname']){
$this->selectDb();
}
}
}
// 获取实例方法
public static function getDb(){
if(!self::$db instanceof self){

self::$db=new self();

}

return self::$db;
}

//防止克隆

final private function __clone(){

}
//设置字符集方法
public function charset(){
$this->exec('set names '.$this->config['charset']);
}
//选择数据库方法
public function selectDb(){
$this->exec('use '.$this->config['dbname']);
}
//数据库语句执行方法,返回resource
public function query($sql){
$res=mysql_query($sql,$this->con);
if($res){
return $res;
}else{
echo 'SQL语句错误:'.$this->getError();
exit;
}
}
//数据库语句执行方法,返回影响行数
public function exec($sql){
$res=mysql_query($sql,$this->con);
if($res){
return $this->getAffRows();
}else{
echo 'SQL语句错误:'.$this->getError();
exit;
}
}
//取出单行单列数据,返回字符串
public function getOne($sql){
$resource=$this->query($sql);
if($this->getResRows($resource)){
$result=mysql_fetch_row($resource);
mysql_free_result($resource);
return $result;
}else{
return false;
}
}
//取出单行多列数据,返回一个数组
public function getRow($sql){
$sql.=$sql.' limit 1';
$resource=$this->query($sql);
if($this->getResRows($resource)){
$result=mysql_fetch_assoc($resource);
mysql_free_result($resource);
return $result;
}else{
return array();
}
}
//取出多行多列数据,返回二维数组
public function getAll($sql){
$resource=$this->query($sql);
if($this->getResRows($resource)){
$res=array();
while($row=mysql_fetch_assoc($resource))
{
$res[]=$row;
}
return $res;
}else{
return array();
}
}

//获取数据库链接
public function getCon(){
return $this->con;
}
//获取错误信息
public function getError(){
return mysql_error();
}
//返回结果集行数
public function getResRows($resource){
return mysql_num_rows($resource);
}
public function getAffRows(){
return mysql_affected_rows($this->con);
}
public function __destruct(){
mysql_close($this->con);
}
}
?>

[隐藏样式|查看源码]


『回复列表(0|隐藏机器人聊天)』

帖子没有回复
回复需要登录

9月15日 21:35 星期一

本站由hu60wap6驱动

备案号: 京ICP备18041936号-1