mysql 單例模式
阿新 • • 發佈:2019-01-06
require_once ('mysql_config.php'); class msyql_db{ static private $_instance; private $com; private function __construct($db_host,$name,$db_name,$db_pwd){ //外部不能直接例項化 $this->com=mysql_connect($db_host,$name,$db_pwd) or die("連結資料庫失敗"); mysql_select_db($db_name); mysql_query("set names utf8"); } private function __clone(){} //外部不能克隆類 static public function instance_com($dbhost,$name,$dbname,$sbpwd){ if(!isset(self::$_instance)){ //self表示類本身 呼叫靜態屬性時要使用 :: self::$_instance= new self($dbhost,$name,$dbname,$sbpwd); //例項化自己 return self::$_instance; }else{ return self::$_instance; } } function select($sql){ //獲得多條資料,二維陣列 $result=mysql_query($sql); $arr=array(); while($row=mysql_fetch_assoc($result)){ $arr[]=$row; } return $arr; } function select1($sql){ $result=mysql_query($sql); return mysql_fetch_assoc($result); } function count($sql){ $result=mysql_query($sql); return mysql_num_rows($result); } function query($sql){ return mysql_query($sql); } function get_last_id(){ $sql="select last_insert_id() as last_id"; $result=mysql_query($sql); $result=mysql_fetch_assoc($result); return $result["last_id"]; } function insert($post){ //insert 語句 合併欄位和對應的值 $cloum=""; $value=""; foreach ($post as $k=>$v){ if ($k!="type"){ $cloum .= ",`".$k."`"; $value .= ",'".$v."'"; } } $cloum=substr($cloum,1); $value=substr($value,1); return array("cloum"=>$cloum,"value"=>$value); } function update($post){ //update 語句 合併欄位和對應的值 $str=""; foreach ($post as $k=>$v){ if ($k!="type"){ $str .= ",`".$k."`='".$v."'"; } } return substr($str,1); } } //$test=new one("localhost","root","online",""); $db = msyql_db::instance_com($db_host,$db_user,$db_db,$db_pwd); //呼叫靜態方法的時候要使用::