一个简单的 php数据库操作类 MysqlDB
发布一个简单的 MysqlDB 类。封装了常用的3个方法。select(), query(), insert()。其中对于 insert() 方法的返回结果是个数组。格式如:array(‘return’=>false,’id’=>NULL)
<?php
/**
* class MysqlDB
*/
class MysqlDB
{
private $host = NULL;
private $user = NULL;
private $password = NULL;
private $dbName = NULL;
private $charset = NULL;
public function MysqlDB($host, $user, $password, $dbName, $charset = 'UTF8')
{
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->dbName = $dbName;
$this->charset = $charset;
}
private function connect()
{
$connectId = mysql_connect($this->host,$this->user,$this->password);
if (!$connectId)
{
if(DEBUG) {
die('Could not connect: '.mysql_error());
}
return NULL;
}
return $connectId;
}
public function select($sql)
{
if(strlen($sql) == 0) {
return NULL;
}
$connectId = $this->connect();
if($connectId == NULL) {
return NULL;
}
mysql_query("SET NAMES $this->charset", $connectId);
mysql_select_db($this->dbName, $connectId);
$queryResult = mysql_query($sql, $connectId);
if(!$queryResult) {
return NULL;
}
$result = array();
while($row = mysql_fetch_array($queryResult))
{
$result[] = $row;
}
mysql_close($connectId);
return $result;
}
public function insert($sql)
{
$result = array('return'=>false, 'id'=>NULL);
if(strlen($sql) == 0) {
return $result;
}
$connectId = $this->connect();
if($connectId == NULL) {
return $result;
}
mysql_query("SET NAMES $this->charset", $connectId);
mysql_select_db($this->dbName, $connectId);
$queryResult = mysql_query($sql, $connectId);
if(!$queryResult) {
return $result;
} else {
$result['return'] = true;
}
$lastInsertId = mysql_insert_id();
mysql_close($connectId);
if($lastInsertId == 0) {
return $result;
} else {
$result['id'] = $lastInsertId;
}
return $result;
}
public function query($sql)
{
if(strlen($sql) == 0) {
return false;
}
$connectId = $this->connect();
if($connectId == NULL) {
return false;
}
mysql_query("SET NAMES $this->charset", $connectId);
mysql_select_db($this->dbName, $connectId);
$result = mysql_query($sql, $connectId);
mysql_close($connectId);
if(!result) {
return false;
} else {
return true;
}
}
}
?>