class MySQLConnFactory
{
private $conn;
static private $_mysqlconn;
//Construct-->connect DB
private function __construct($host,$username,$password)
{
$this->conn = mysql_connect($host,$username,$password);
$this->query("SET NAMES 'utf8'");
return $this->conn;
}
private function __clone(){}
public static function getSingleMySQLConn($host,$username,$password)
{
if(FALSE==(self::$_mysqlconn instanceof self))
{
self::$_mysqlconn = new self($host,$username,$password);
}
return self::$_mysqlconn;
}
//select DB
public function select_db($database)
{
$this->result = mysql_select_db($database);
return $this->result;
}
//Query
public function query($query)
{
return $this->result = mysql_query($query, $this->conn);
}
//fetch result
public function fetch_array($fetch_array)
{
return $this->result = mysql_fetch_array($fetch_array, MYSQL_ASSOC);
}
//close
public function close()
{
return $this->result = mysql_close($this->conn);
}
}
?>
調用方式如下
$sql = "select * from test";
$connector = MySQLConnFactory::getSingleMySQLConn($db_server,$db_user,$db_pwd);
$connector -> select_db($db_name);
$result = $connector -> query($sql);