php为操作mysql提供了一些简单易用的函数mysql_connect,mysql_query,mysql_fetch_array等,想对它们做一个简单的封装,这里使用基本的mysql_connect函数而不是保持连接的mysql_pconnect函数。
<?php
/**
* @author pengjing
* @copyright 2012
*/
class EasyMysql
{
/**
* configuration
*/
private $host;
private $port;
private $username;
private $password;
private $dbname;
private $charset;
/**
* database object
*/
private $conn;
/**
* error information
*/
private $errno;
private $error;
/**
* EasyMysql::__construct()
*
* @return
*/
function __construct()
{
$this->host = "localhost";
$this->port = 3306;
$this->username = "";
$this->password = "";
$this->dbname = "test";
$this->charset = "gbk";
$this->conn = $this->connect();
}
/**
* EasyMysql::__destruct()
*
* @return
*/
function __destruct()
{
if($this->conn){
mysql_close($this->conn);
}
}
/**
* EasyMysql::query()
*
* @param mixed $sql
* @return
*/
public function query( $sql )
{
$data = Array();
$i = 0;
$result = mysql_query($sql, $this->conn);
$this->save_error($dblink);
if(is_bool($result)){
return $result;
}
else
{
while( $arr = mysql_fetch_array($result,MYSQL_ASSOC))
{
$data[$i++] = $arr;
}
}
mysql_free_result($result);
if(count($data) > 0)
{
return $data;
}
else{
return NULL;
}
}
/**
* EasyMysql::connect()
*
* @param bool $is_master
* @return
*/
private function connect()
{
$conn = mysql_connect($host, $this->username, $this->password);
if( !$conn )
{
$this->error = mysql_error();
$this->errno = mysql_errno();
return NULL;
}
if( !mysql_select_db($this->dbname) ) {
return NULL;
}
if(isset($this->charset))
{
mysql_query( "set names $this->charset" );
}
return $conn;
}
/**
* EasyMysql::save_error()
*
* @param mixed $dblink
* @return
*/
private function save_error($dblink)
{
$this->errno = mysql_errno();
$this->error = mysql_error();
}
/**
* EasyMysql::error()
*
* @return
*/
public function error(){
return $this->error;
}
/**
* EasyMysql::errno()
*
* @return
*/
public function errno(){
return $this->errno;
}
}
?>
使用方法如下,包含easymysql库文件,创建一个操作对象$my
<?php
include("EasyMysql.php");
$my = new EasyMysql();
$res = $my->query("select * from a");
print_r($res);
/*
Array
(
[0] => Array
(
[id] => 3
[name] => Hello
)
[1] => Array
(
[id] => 4
[name] => World
)
)
*/
$res = $my->query("insert into a values(6,'baibai')");
print_r($res);
/*
1
*/
$res = $my->query("delete from a where id=6");
print_r($res);
/*
1
*/
$res = $my->query("select count(*) from a");
print_r($res);
/*
Array
(
[0] => Array
(
[count(*)] => 2
)
)
*/
$res = $my->query("select count(*) from b");
print_r($res);
print_r($my->errno());
print_r($my->error());
/*
1146 Table 'test.b' doesn't exist
*/
?>