思路,通過前面面向對象的開發,考慮能夠把PHP對MYSQL數據庫的操做封裝到一個類中,經過面向對象的方式開發。php
首先創建 mysql_class.phphtml
- <?
- class mysql {
- private $name;
- private $pass;
- private $host;
- private $table;
- function __construct($host,$name,$pass,$table){
- $this->host=$host;
- $this->name=$name;
- $this->pass=$pass;
- $this->table=$table;
- $this->connect();
- }
- function connect(){
- $db=mysql_connect($this->host,$this->name,$this->paass) or die (mysql_error());
- mysql_select_db($this->table,$db) or die ("沒有該數據庫".$this->table);
- }
- function query($v)
- {
- $query = mysql_query($v) ;
- return $query;
- }
- function fn_select($table,$num){
- return $this->query("select * from $table limit $num ");
- }
- function fn_insert($table,$name,$value){
- $this->query("insert into $table ($name)value($value)");
- }
- function error(){
- return mysql_error();
- }
- function __call($n,$v){
- echo "錯誤的方法爲".$n;
- echo "錯誤的值爲".print_r($v);
- }
- }
- ?>
二,在須要的頁面用自動加載函數加載實例化對象的方式來輸出mysql
- <?
- header("Content-Type:text/html; charset=utf-8");
- function __autoload($name){
- include ($name."_class.php");
- }
- $db = new mysql("localhost","root","","youbaopaidakuo");
- $db->query("set names utf8");
- $query = $db->fn_select("ecm_article",20);
- while($arr=mysql_fetch_array($query))
- {
- echo $arr[title]."<br>";
- }
- ?>