<?php
class Mysql{
private static $_instance;
private $_db;
public function __clone(){
}
private function __construct($host,$usr,$pass,$port){
$this->_db = $this->db($host,$usr,$pass,$port);
}
public static function getInstance($host,$usr,$pass,$port){
if(!isset(self::$_instance) || !(self::$_instance instanceof self)){
//echo ‘init db instance’;
self::$_instance = new self($host,$usr,$pass,$port);
}
return self::$_instance;
}
private function db($host,$usr,$pass,$port=3306){
$mysqli = new mysqli($host,$usr,$pass,”,$port);
if ($mysqli->connect_error) {
die(‘Connect Error (‘ . $mysqli->connect_errno . ‘) ‘. $mysqli->connect_error);
}
return $mysqli;
}
public function query($sql){
$result = $this->_db->query($sql);
return $result;
}
public function fetch_assoc($sql){
$result = $this->query($sql);
$rows = array();
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
return $rows;
}
public function close(){
if(isset($this->_db) && !empty($this->_db)){
$this->_db->close();
}
}
}
/** * test case */ /* $host='localhost'; $user='root'; $pass='root'; $port=3306; $instance = Mysql::getInstance($host,$user,$pass,$port); $result = $instance->fetch_assoc('select * from test.lee limit 5'); $result = $instance->query("insert into test.lee values(null,'guest02',now());"); print_r($result); */ ?>