代码:
<?php /** * desc:mysql操作类 * filename:db.class.php * by www.jb200.com */ Class db { //数据库配置信息 private $Host='localhost'; private $UserName='root'; private $Password=''; private $DbName='dbname'; //根据自己的实际情况修改 public $link; public $query; public $last_error; function __construct() { $this->Connect(); } function __destruct() { $this->Close(); } private function Connect() { //数据库连接 $this->link=mysql_connect($this->Host,$this->UserName,$this->Password) or die("Error Connect to DB"); $this->SetError(mysql_error()); //select db ... mysql_select_db($this->DbName) ;//or die("Error Select DB"); $this->SetError(mysql_error()); } public function query($query) { //mysql查询 $this->query=mysql_query($query,$this->link); $this->SetError(mysql_error()); } public function assoc() { //mysql_fetch_assoc : return mysql_fetch_assoc($this->query); $this->SetError(mysql_error()); } public function num() { //mysql_num_rows: return mysql_num_rows($this->query); $this->SetError(mysql_error()); } public function result($index=0) { //mysql_result : return mysql_result($this->query,$index); $this->SetError(mysql_error()); } private function SetError($error) { $this->last_error=$error; } public function ShowError() { return $this->last_error; } private function Close() { mysql_close($this->link); } } ?>
调用示例:
<?php // include class : require_once "db.class.php"; //creat a db object $con=new db; //run the query: $con->query("select * from table "); //get number of result echo $con->num() . PHP_EOL; //get result echo $con->result(/* $index */) . PHP_EOL; //get all result while($row=$con->assoc()) var_dump($row);