標籤:port blog ret span dbn static pre 使用 構造
PHP代碼展示:
1 <?php 2 //類名,也習慣上(推薦)使用跟檔案名稱相似的名字 3 //定義一個類,該類可以串連mysql資料庫 4 //並串連後返回資源(或失敗就終止) 5 class mysqlDB{ 6 public $host; 7 public $port; 8 public $username; 9 public $password;10 public $charset;11 public $dbname;12 13 //串連結果(資源)14 static $link;15 16 //建構函式17 public function __construct($config){18 //初始化資料19 $this->host = isset($config[‘host‘]) ? $config[‘host‘] : ‘localhost‘;20 $this->port = isset($config[‘port‘]) ? $config[‘port‘] : ‘3306‘;21 $this->username = isset($config[‘username‘]) ? $config[‘username‘] : ‘root‘;22 $this->password = isset($config[‘password‘]) ? $config[‘password‘] : ‘‘;23 $this->charset = isset($config[‘charset‘]) ? $config[‘charset‘] : ‘utf8‘;24 $this->dbname = isset($config[‘dbname‘]) ? $config[‘dbname‘] : ‘‘;25 26 //串連資料庫27 self::$link = $this->connect();28 //設定串連編碼29 $this->setCharset($this->charset);30 //選定資料庫31 $this->selectDb($this->dbname);32 }33 //這裡進行串連34 public function connect(){35 $link = mysql_connect("$this->host:$this->port", "$this->username","$this->password") or die("串連資料庫失敗!");36 return $link;37 }38 public function setCharset($charset){39 mysql_set_charset($charset, self::$link); 40 }41 public function selectDb($dbname){42 mysql_select_db($dbname, self::$link) 43 }44 }45 46 //先設想:47 $config = array(48 ‘host‘=>‘localhost‘,49 ‘port‘=>‘3306‘,50 ‘username‘=>‘root‘,51 ‘password‘=>‘123‘,52 ‘charset‘=>‘utf8‘,53 ‘dbname‘=>‘php34‘,54 );55 $link = new mysqlDB( $config );56 $result = $link->query("delete from tab1 where id=1");
大概就是這個樣子,我沒有試,不過思路就是這個。
28)PHP,資料庫連接類