Home  >  Article  >  Backend Development  >  A php and mysql connection class

A php and mysql connection class

WBOY
WBOYOriginal
2016-07-25 08:56:47837browse
This article introduces a good php and mysql connection class, implemented in php5. Friends in need can refer to it.

Code:

<?php 
/**
* desc:mysql操作类
* filename:db.class.php
* by bbs.it-home.org
*/
 
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);
}
}
?>

Call example:

<?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);


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn