本文介绍下,一个不错的php与mysql连接类,php5实现的,有需要的朋友参考下吧。
代码:
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);
}
}
?>
调用示例:
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);