本文實例講述了php封裝的連接Mysql類及用法。分享給大家供大家參考,具體如下:
class mysql{ private $db_name; private $db_host; private $db_user; private $db_pwd; private $conn; private $querysql; private $result; private $resultarray=array(); private $row; //創建構造函數 數據庫名 主機名 用戶名 密碼 function __counstruct($dbname,$dbhost,$dbuser,$dbpwd){ $this->db_name=$dbname; $this->db_host=$dbhost; $this->db_pwd=$dbpwd; $this->db_user=$dbuser; $this->dbconnect(); $this->selectdb(); } //連接數據庫 private function db_connect(){ $this->conn=mysql_connect($this->db_host,$this->db_user,$this->db_pwd) or die("Could not Connect MySql Server"); } private function selectdb(){ mysql_select_db($this->db_name) or die("unable to select dbname") } private function query(){ return $this->result=mysql_query($this->querysql); } private function get_result($sql){ $this->querysql=$sql; $this->query(); if($this->get_num()>0){ //mysql_fetch_assoc()和 mysql_fetch_array(,MYSQL_ASSOC)從結果集中取得一行作為關聯數組 沒有則返回false while($this->rows=mysql_fetch_array($this->result)){ //賦值 數組賦值 resultarray[]= 將影響的行數賦值給數組 $this->resultarray[]=$this->rows } return $this->resultarray; } } //$result返回值為 bool類型 false為沒有數據 private function get_num(){ return $this->num=mysql_num_rows($this->result); } } $m=new mysql("testuser","localhost","root","root"); $arreresult=$m->get_result("select * from userinfo");
希望本文所述對大家php程序設計有所幫助。