dbMySQL类,用于PHP访问MySQL数据库,而编程更加方便、安全性更高。
<?php
class dbMySQL {
private $conn;
private $prefix;
private $sql=NULL;
private $result=NULL;
private $rows=0;
private $rows_got=0;
function __construct($host,$username,$password,$dbname,$prefix='',$pconnect=TRUE) {
$connect_function=$pconnect?'mysql_pconnect':'mysql_connect';
$this->conn=@$connect_function($host,$username,$password) or die('不能连接到MySQL数据源服务');
mysql_query("SET NAMES 'utf8'",$this->conn);
@mysql_select_db($dbname,$this->conn) or die('MySQL数据源中数据库不存在');
$this->prefix=$prefix;
}
private function close() {
if ($this->result!=NULL) mysql_free_result($this->result);
}
public function execute_sql($SQL) {
$this->close();
$this->sql=$SQL;
mysql_query($SQL,$this->conn);
$err=mysql_error($this->conn); if ($err!='') die($err);
$this->result=NULL;
$this->rows=mysql_affected_rows($this->conn);
$this->rows_got=0;
}
public function execute($SQL,$p=NULL,$prefix='###') {
$s=str_replace($prefix,$this->prefix,$SQL);
if ($p==NULL) { $this->execute_sql($s); return; }
foreach ($p as $i => $v) {
if (ctype_digit($i{0}) && !is_numeric($v)) die('SQL数值型参数错误 '.$i.'=>'.$v);
$vv=ctype_lower($i{0})?"'".mysql_escape_string($v)."'":$v;
$s=str_replace('?'.$i,$vv,$s);
}
$this->execute_sql($s);
}
public function query_sql($SQL) {
$this->close();
$this->sql=$SQL;
$this->result=mysql_query($SQL,$this->conn);
$err=mysql_error($this->conn); if ($err!='') die($err);
$this->rows=mysql_num_rows($this->result);
$this->rows_got=0;
}
public function query($SQL,$p=NULL,$prefix='###') {
$s=str_replace($prefix,$this->prefix,$SQL);
if ($p==NULL) { $this->query_sql($s); return; }
foreach ($p as $i => $v) {
if (ctype_digit($i{0}) && !is_numeric($v)) die('SQL数值型参数错误 '.$i.'=>'.$v);
$vv=ctype_lower($i{0})?"'".mysql_escape_string($v)."'":$v;
$s=str_replace('?'.$i,$vv,$s);
}
$this->query_sql($s);
}
public function read() {
if ($this->result==NULL) return NULL;
if ($this->rows_got==$this->rows) return NULL;
++$this->rows_got;
return mysql_fetch_assoc($this->result);
}
public function num_rows() {
return $this->rows;
}
public function eof() {
return ($this->rows_got==$this->rows);
}
}
?>
dbMySQL优点
- 高安全性:强制检查类型、自动转义,避免SQL注入漏洞
- 方便编程:面向对象语法,不必写mysql_fetch_assoc等长长的函数名
- 方便编程:仿reader机制,直接从对象读出数据,不必再写$resultID
- 支持表名前缀:允许在一个数据库中运行多个应用
dbMySQL样例代码