思路,经过前面面向对象的开发,考虑可以把PHP对MYSQL数据库的操作封装到一个类中,通过面向对象的方式开发。
首先建立 mysql_class.php
- <?
- 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);
- }
- }
- ?>
二,在需要的页面用自动加载函数加载实例化对象的方式来输出
- <?
- 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>";
- }
- ?>
转载于:https://blog.51cto.com/phpmylove/678791