PHP中封裝mysql資料庫連結(簡單版)

來源:互聯網
上載者:User
1,封裝mysql資料連結需要哪些屬性

主機地址,資料庫名,資料庫密碼,資料庫名,字元集

2,利用構造方法在執行個體化類時,php底層會自動執行的特性來封裝一個資料庫連結類

3,在執行個體化類時給它傳一個參數(數組),參數裡麵包括需要用到的資料

class Dbname{public $host;           //主機地址,這裡資料庫連接埠預設為3306public $user;           //資料庫使用者名稱public $pass;           //資料庫密碼public $dbname;         //資料庫名public $link;           //資料庫連結名public $char;           //字元集public $sql;            //sql語句public function __construct($db){$this->host=$db['host'];$this->user=$db['user'];$this->pass=$db['pass'];$this->dbname=$db['dbname'];$this->char=$db['char'];//連結資料庫$this->dbSql();//選擇資料庫$this->seleDb();//設定字元集$this->setChar();//執行mysql查詢語句$this->execute_dml();}//連結資料庫public function dbSql(){$this->link=mysql_connect($this->host,$this->user,$this->pass) or die('連結資料庫失敗');}//選擇資料庫public function seleDb(){mysql_select_db($this->dbname,$this->link);}//設定字元集public function setChar(){mysql_set_charset($this->char,$this->link);}}    //執行mysql查詢語句public function execute_dml($this->sql)    {        $data=array();        $res=mysql_query($this->sql);        while($row = mysql_fetch_assoc($res))        {            $data[] = $row;        }       return $data;    }

以上就是封裝一個簡單的資料庫連結類,並執行一條sql查詢語句返回一個數組

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.