PHP单例模式封装Mysql数据库
<?php
class MySQLDB{
public $host;
public $port;
public $username;
public $password;
public $charset;
public $dbname;
private static $link;
private $resourc;
public static function getInstance($config){
if(!isset(self::$link)){
self::$link = new self($config);
}
return self::$link;
}
private function __construct($config){
$this->host = isset($config['host']) ? $config['host'] : 'localhost';
$this->port = isset($config['port']) ? $config['port'] : '3306';
$this->username = isset($config['username']) ? $config['username'] : 'root';
$this->password = isset($config['password']) ? $config['password'] : '';
$this->charset = isset($config['charset']) ? $config['charset'] : 'utf8';
$this->dbname = isset($config['dbname']) ? $config['dbname'] : '';
$this->connect();
$this->setCharset($this->charset);
$this->selectDb($this->dbname);
}
private function __clone(){}
public function connect(){
$this->resourc = mysql_connect("$this->host:$this->port", "$this->username","$this->password") or die("连接数据库失败!");
}
public function setCharset($charset){
mysql_set_charset($charset, $this->resourc);
}
public function selectDb($dbname){
mysql_select_db($dbname, $this->resourc);
}
public function query($sql){
if(!$result = mysql_query($sql, $this->resourc))
{
echo ("<br />执行失败。");
echo "<br />失败的sql语句为:" . $sql;
echo "<br />出错信息为:" . mysql_error();
echo "<br />错误代号为:" . mysql_errno();
die();
}
return $result;
}
public function getAll($sql){
$result = $this->query($sql);
$arr = array();
while( $rec = mysql_fetch_assoc( $result )){
$arr[] = $rec;
}
return $arr;
}
public function getRow($sql){
$result = $this->query($sql);
if( $rec2 = mysql_fetch_assoc( $result )){
return $rec2;
}
return false;
}
public function getOne($sql){
$result = $this->query($sql);
$rec = mysql_fetch_row($result);
if($result === false){
return false;
}
return $rec[0];
}
}