<?
Class MySql_Engine extends InsecurityItem
{
/* MySql 私有函数
Private Parameter 1 : MySql 登陆帐号
Private Parameter 2 : MySql 登陆密码
Private Parameter 3 : MySql 连接主机
Private Parameter 4 : 是否自动连接 MySql
private Parameter 5 : 是否创建永久连接
Private Parameter 6 : 语言区

for Yan Jing Ning At 9/2/2007
*/
private $_SQLROOTNAME = '';
private $_SQLROOTPASS = '';
private $_SQLROOTHOST = '';
private $_AUTOCONNECT;
private $_PCONNECT;
private $_CHARSET;

/* MySql 连接资源 */
private $_MYRESOURCE;

/* MySql 当前执行的SQL语句 */
public $CurrentSql;

/* 类私有记录集 */
public $_Result;
private $_RecSum;

public $effectID;
public $RecorderTotal;
/* 查询数据是否存在,贯连 Qurey 函数查询时,得到结果
请参考 Qurey 含数 */
public $IsExist = null;

/* 构造函数,传递MySql常规参数

当 $Arp 为一个数组时(且数组为合法的SQL数组),跟后参数全部失效。
否则 $Arp 将设置为 Null ,后面参数必须认真填写 */
/* 数组例子:
$SqlParamter = array(
$MySql_Host,
$MySql_Root,
$MySql_Pass,
$MySql_Charset,
$MySql_PConnect,
$MySql_AutoConnect,
$MySql_DataBase,
$MySql_SaveLog,
$MySql_SaveLogFile);
*/
public function MySql_Engine($Arp = null,$SqlHost = 'localhost',$SqlUid = 'root',$SqlPwd = null,
$Charset = 'UTF8',$pconnect = false,$AutoConn = true,
$DataBase = null,$SaveLogFile = false,$LogFilePath = 'DB_Operate')
{
/* 初始化特殊功能使用安全码 */
$this->SafelyNumber = '';
/* 继承到特殊功能类的连接资源 */
$this->_Connect = '';

if($Arp == null) //如果不是数组,数据库函数的处理
{
$this->_SQLROOTHOST = $SqlHost;
$this->_SQLROOTNAME = $SqlUid;
$this->_SQLROOTPASS = $SqlPwd;
$this->_CHARSET = $Charset;
$this->_PCONNECT = $pconnect;
$this->_AUTOCONNECT = $AutoConn;
$this->_DataBase = $DataBase;
$this->SaveLogFile = $SaveLogFile;
$this->LogFilePath = $LogFilePath;
} else { //如果是数组 ,数据库函数的处理
$parameterArl = $Arp; //将数组传递给 $parameterArl
if(is_array($parameterArl))
{
$this->_SQLROOTHOST = $parameterArl[0];
$this->_SQLROOTNAME = $parameterArl[1];
$this->_SQLROOTPASS = $parameterArl[2];
$this->_CHARSET = $parameterArl[3];
$this->_PCONNECT = $parameterArl[4];
$this->_AUTOCONNECT = $parameterArl[5];
$this->_DataBase = $parameterArl[6];
$this->SaveLogFile = $parameterArl[7];
$this->LogFilePath = $parameterArl[8];
} else {
$this->LogRecorder('Parameter Not Array',1);
return false;
}
}

$this->LogRecorder('Let Parameter',0);

/* 如果 $this->_AUTOCONNECT 函数为 true 则 自动连接数据库
否则 需要手动连接连接,即需调用 $this->DataBase() 含数 */
if($this->_AUTOCONNECT)
{
$this->LogRecorder('Auto Connect MySql',0);
$this->Connect();

/* 如果 $DataBase 为 null,则不自动选择数据库,否则自动选择操作数据库 */
if($this->_DataBase !== null)
{
$this->LogRecorder('Auto Select DB',0);
$this->DataBase($this->_DataBase);
} else {
$this->LogRecorder('Manual Select DB , The DataBase Is Empty',0);
}
}
}

/* 输入特殊功能安全码 */
public function SafelyNumber($SafelyNum)
{
$this->SafelyNumber = $SafelyNum;
}

/* MySql 连接 */
public function Connect()
{
if($this->_PCONNECT) //当 $this->PCONNECT 为 True 使用持久连接
{
$this->_MYRESOURCE = @mysql_pconnect($this->_SQLROOTHOST,$this->_SQLROOTNAME,$this->_SQLROOTPASS);
mysql_query("SET NAMES '" . $this->_CHARSET . "'"); //设置语区
$this->_Connect = $this->_MYRESOURCE; //将本类的连接资源传递给特殊功能类的连接资源
$this->LogRecorder('Connect Way : pConnect ',0);
} else { //否则使用普通连接
$this->_MYRESOURCE = @mysql_connect($this->_SQLROOTHOST,$this->_SQLROOTNAME,$this->_SQLROOTPASS);
mysql_query("SET NAMES '" . $this->_CHARSET . "'"); //设置语区
$this->_Connect = $this->_MYRESOURCE; //将本类的连接资源传递给特殊功能类的连接资源
$this->LogRecorder('Connect Way : Narmal Connect ',0);
}

if($this->_MYRESOURCE == false)
{
$this->LogRecorder('Connect Lost ' . mysql_errno() . ":" . mysql_error(),1);
} else {
$this->LogRecorder('Connect Succeed , ID is ' . $this->_MYRESOURCE,0);
}
}

/* MySql 断开连接 */
public function Disconnect()
{
if($this->_PCONNECT) // 如果使用持久连接,则 Disconnect 函数使用无效
{
$this->LogRecorder('PConnect Not Use Disconnect',1);
} else {
$this->LogRecorder('Try Disconnect ID is ' . $this->_MYRESOURCE,0);
$CloseResource = @mysql_close($this->_MYRESOURCE);
if($CloseResource)
{
$this->LogRecorder('Disconnect Succeed ',0);
} else {
$this->LogRecorder('Disconnect Lost ' . mysql_errno() . ":" . mysql_error(),1);
}
}
}

/* 选择操作数据库 */
public function DataBase($DataBase)
{
$SDB = @mysql_select_db($DataBase,$this->_MYRESOURCE);
if($SDB)
{
$this->LogRecorder('Select DataBase Succeed ',0);
} else {
$this->LogRecorder('Select DataBase Lost ' . mysql_errno() . ":" . mysql_error(),1);
}
}

/* 执行 SQL 语言查询 */
public function Query($m_Sql,$method='CACHE')
{
$this->CurrentSql = $m_Sql; // 当前SQL语句
if($method == 'NOCACHE')
{
/* 不缓存数据记录集 */
$this->_Result = @mysql_unbuffered_query($m_Sql,$this->_MYRESOURCE);
/* 把记录集传递给高级功能类的记录集中 */
$this->_InsecQry = $this->_Result;
} else {
/* 缓存数据记录集 */
$this->_Result = @mysql_query($m_Sql,$this->_MYRESOURCE);
$this->_InsecQry = $this->_Result;
}

/* $IsExist 判断 ;
查询记录集中的数据库行数;
如果等于 0 ,则不存在,否则存在;
$this->RecorderTotal 用户返回记录集中有多少条数据 */
if(@mysql_num_rows($this->_Result) == 0)
{
$this->IsExist = false;
$this->RecorderTotal = 0;
} else {
$this->IsExist = true;
$this->RecorderTotal = @mysql_num_rows($this->_Result);
}
if($this->_Result == false)
{
$this->LogRecorder('Get Results Lost , ' . mysql_errno() . ":" . mysql_error() ,1);
return false;
} else {
$this->LogRecorder('Get Results Succeed , method is ' . $method ,0);
return true;
}
}

/* 统一执行语句参数 */
public function Execute($Sql = '')
{
if($Sql == '') // 如果$Sql为空,则不执行操作
{
$this->LogRecorder('$Sql is Empty ' ,1);
return false;
} else {
$_Execute = @$this->Query($Sql);
if($_Execute)
{
$this->LogRecorder("Execute '" . $Sql . "' Succeed , Last inserted id " . @mysql_insert_id(),0);
$this->effectID = @mysql_insert_id();
return true;
} else {
$this->LogRecorder("Execute '" . $Sql . "' Lost ",1);
return false;
}
}
}
/* 常规模式:插入一条记录到数据库 */
/* 返回 False 执行失败 ,反之 */
public function Insert($Sql = '')
{
if($Sql == '') // 如果$Sql为空,则不执行操作
{
$this->LogRecorder('$Sql is Empty ' ,1);
return false;
} else {
$_Insert = @$this->Query($Sql);
if($_Insert)
{
$this->LogRecorder("INSERT '" . $Sql . "' Succeed , Last inserted id " . @mysql_insert_id(),0);
$this->effectID = @mysql_insert_id();
return true;
} else {
$this->LogRecorder("INSERT '" . $Sql . "' Lost ",1);
return false;
}
}
}
/* 高级模式:插入一条记录到数据库
$tabel 为数据表名
$key 为 字段名
$value 为 对应字段的数据 */
/* 返回 False 执行失败 ,反之 */
public function Insert_r($tabel,$key = null,$value = null)
{
if((is_array($key) == false) || (is_array($value) == false))
{
$this->LogRecorder('$key or $value Not Array or Empty ' ,1);
} else {
$this->LogRecorder('Array Let Parameter Sueeccd ' ,0);
}

$_Key = '';
$_Value = '';

foreach($key as $Keys) // 字段名重排
{
if($_Key == '')
{
$_Key = $Keys;
} else {
$_Key = $_Key . ',' . $Keys;
}
}

foreach($value as $Values) // 数据重排
{
if($_Value == '')
{
$_Value = $Values;
} else {
$_Value = $_Value . ',' . $Values;
}
}

// 组合SQL语句
$Sql = 'INSERT INTO ';
$Sql = $Sql . $tabel . ' ';
$Sql = $Sql . '(' . $_Key . ')' . ' ';
$Sql = $Sql . 'VALUES' . ' ';
$Sql = $Sql . '(' . $_Value . ')' . ' ';

// 执行SQL语句
$_Insert = @$this->Query($Sql);
if($_Insert)
{
$this->LogRecorder("INSERT '" . $Sql . "' Succeed , Last inserted id " . @mysql_insert_id(),0);
$this->effectID = @mysql_insert_id();
return true;
} else {
$this->LogRecorder("INSERT '" . $Sql . "' Lost ",1);
return false;
}
}

/* 普通模式:在数据库中删除一条数据 */
/* 返回 False 执行失败 ,反之 */
public function Delete($Sql)
{
if($Sql == '')
{
$this->LogRecorder('$m_Sql is Empty ' ,1);
return false;
} else {
// 执行删除
$_Delete = @$this->Query($Sql);
if($_Delete)
{
$this->LogRecorder("DELETE '" . $Sql . "' Succeed ",0);
$this->effectID = @mysql_affected_rows(); // 删除后,返回所有影响的记录ID
if(($this->effectID == 0) || ($this->effectID < 0))
{
return false;
} else {
return true;
}
} else {
$this->LogRecorder("DELETE '" . $Sql . "' Lost ",1);
return false;
}
}
}
/* 高级模式:在数据库中删除一条数据 */
/* 返回 False 执行失败 ,反之
$tabel 为 表名
$value 为 查找删除数据的条件
如果 $value 为 null 则删除此表中所有数据 */
public function Delete_r($tabel,$Value = null)
{
$Sql = 'DELETE FROM ';
$Sql = $Sql . $tabel;
if($Value !== null) // 重排查询条件
{
$Sql = $Sql . ' WHERE ';
$Sql = $Sql . $Value;
}
//执行删除
$_Delete = @$this->Query($Sql);

if($_Delete)
{
$this->LogRecorder("DELETE '" . $Sql . "' Succeed ",0);
$this->effectID = @mysql_affected_rows(); // 删除后,返回所有影响的记录ID
if(($this->effectID == 0) || ($this->effectID < 0))
{
return false;
} else {
return true;
}
} else {
$this->LogRecorder("DELETE '" . $Sql . "' Lost ",1);
return false;
}
}

/* 普通模式:更新数据库中已存在的一条数据 */
/* 返回 False 执行失败 ,反之 */
public function Update($Sql)
{
$_Update = @$this->Query($Sql);
if($_Update)
{
$this->LogRecorder("UPDATE '" . $Sql . "' Succeed ",0);
$this->effectID = @mysql_affected_rows();
if(($this->effectID == 0) || ($this->effectID < 0))
{
$this->LogRecorder('Data No Exist',1);
return false;
} else {
$this->LogRecorder('Data Exist',1);
return true;
}
} else {
$this->LogRecorder("UPDATE '" . $Sql . "' Lost ",1);
return false;
}
}
/* 高级模式:更新数据库中已存在的一条数据 */
/* 返回 False 执行失败 ,反之
$tabel 为 表名
$value 为 字段名 和 对应数据
$Condition 为更新操作条件 */
public function Update_r($tabel,$value,$Condition = null)
{
$_tmpType = '';
$n = 0;
/*
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
reset ($fruit);
while (list ($key, $val) = each ($fruit)) {
echo "$key => $val ";
}
*/
/* Outputs:
a => apple
b => banana
c => cranberry
*/

if(is_array($value)) // 分解数组并重新组合为字符串
{
reset($value);
$fruit = $value;
while (list ($key, $val) = each ($fruit)) {
if ($n == 0)
{
$_tmpType = '`' . $key . '`' . " = " . $val;
} else {
$_tmpType = $_tmpType . ",`" . $key . "` = " . $val;
}
$n++;
}
$Sql = 'UPDATE ';
$Sql = $Sql . '`' . $tabel . '`';
$Sql = $Sql . ' SET ';
$Sql = $Sql . $_tmpType;
if($Condition !== null)
{
$Sql = $Sql . ' WHERE ' . $Condition;
}
$_Update = @$this->Query($Sql);
if($_Update)
{
$this->LogRecorder("UPDATE '" . $Sql . "' Succeed ",0);
$this->effectID = @mysql_affected_rows();
if(($this->effectID == 0) || ($this->effectID < 0))
{
$this->LogRecorder('Data No Exist',1);
return false;
} else {
$this->LogRecorder('Data Exist',1);
return true;
}
} else {
$this->LogRecorder("UPDATE '" . $Sql . "' Lost ",1);
return false;
}
} else {
$this->LogRecorder('Let Update Parameter Not Array ' ,0);
return false;
}
}

/* 返会记录数组 */
/* $Row[] 返回 False 或 不是 Array时, 代表数据不存在
$method 为 NUM 时,返回一个以 数字 为索引的数组
为 ASSOC 时,返回一个以 字段名 为索引的数组
默认为 MYSQL_BOTH ,不设置 $method 或空时
*/
public function fetch_array($method = '',$QueryMethod='NOCACHE',$m_Sql = null)
{
$this->LogRecorder('Extraction Recorder method is mysql_fetch_array ' ,0);
if($m_Sql !== null)
{
$this->Query($m_Sql,$QueryMethod);
}

switch ($method)
{
case 'NUM';
while($Tmp=@mysql_fetch_array($this->_Result,MYSQL_NUM))
{
$Row[] = $Tmp;
}
if($Row)
{
$this->LogRecorder('Extraction Recorder Sueeccd , method is MYSQL_NUM' ,0);
} else {
$this->LogRecorder('Extraction Recorder Lost , method is MYSQL_NUM',1);
}
break;
case 'ASSOC';
while($Tmp=@mysql_fetch_array($this->_Result,MYSQL_ASSOC))
{
$Row[] = $Tmp;
}

if($Row)
{
$this->LogRecorder('Extraction Recorder Sueeccd , method is MYSQL_ASSOC' ,0);
} else {
$this->LogRecorder('Extraction Recorder Lost , method is MYSQL_ASSOC',1);
}
break;
default:
while($Tmp=@mysql_fetch_array($this->_Result,MYSQL_BOTH))
{
$Row[] = $Tmp;
}

if($Row)
{
$this->LogRecorder('Extraction Recorder Sueeccd , method is SYNTHESIZE' ,0);
} else {
$this->LogRecorder('Extraction Recorder Lost , method is SYNTHESIZE',1);
}
}
$this->ResultFree($this->_Result);
return $Row;
}

/* 结果以对象方式返回数组 */
/* $Row[] 返回 False 或 不是 Array时, 代表数据不存在 */
public function fetch_object($m_Sql = null,$QueryMethod='NOCACHE')
{
$this->LogRecorder('Extraction Recorder method is mysql_fetch_object' ,0);

if($m_Sql !== null)
{
$this->Query($m_Sql,$QueryMethod);
}

while($Tmp=@mysql_fetch_object($this->_Result))
{
$Row[] = $Tmp;
}

if($Row)
{
$this->LogRecorder('Extraction Recorder Object Array Sueeccd ' ,0);
} else {
$this->LogRecorder('Extraction Recorder Object Array Lost ',1);
}
$this->ResultFree($this->_Result);
return $Row;
}

/* 记录下移一行 */
public function DataSeek($i)
{
$_isSeek = @mysql_data_seek($this->_Result,$i);
if($_isSeek)
{
return true;
} else {
return false;
}
}

/* 特殊功能:创建一个数据库,必须先设置特殊功能安全码 */
public function CreateDataBase($DataBaseName)
{
if($this->Advance())
{
$this->LogRecorder('Safely Number Error' ,1);
die('Insecurity : Use invalidation for Insecurity Item');
}
$_CreateDB = @$this->Query("Create Database $DataBaseName");
if($_CreateDB)
{
$this->LogRecorder('Create DataBase ' . $DataBaseName . ' Sueeccd ',0);
} else {
$this->LogRecorder('Create DataBase ' . $DataBaseName . ' Lost ' ,1);
}
}

/* 特殊功能:移除一个数据库,必须先设置特殊功能安全码 */
public function DropDataBase($DataBaseName)
{
if($this->Advance())
{
$this->LogRecorder('Safely Number Error' ,1);
die('Insecurity : Use invalidation for Insecurity Item');
}
$_DropDB = @$this->Query("DROP DATABASE $DataBaseName");
if($_DropDB)
{
$this->LogRecorder('Drop DataBase ' . $DataBaseName . ' Sueeccd ',0);
} else {
$this->LogRecorder('Drop DataBase ' . $DataBaseName . ' Lost ',1);
}
}

/* 释放资源 */
private function ResultFree($Result)
{
$_FreeMemory = @mysql_free_result($Result);
if($_FreeMemory)
{
$this->LogRecorder('free memory Succeed ',0);
} else {
$this->LogRecorder('free memory Lost ',1);
}
}
/* __call 如果找不到函数,则返回错误信息 */
public function __call($function_name,$args)
{
$this->LogRecorder('find not function ',1);
}
}

/* 特殊功能类 */
Class InsecurityItem
{
protected $SafelyNumber = ''; //安全码
private $SetSafelyNumber = 'AdvanceUse'; //定义安全码

/* 资源信息传递 */
protected $_InsecQry; // 记录集资源
protected $_Connect; // 连接资源

/* 日志记录参数 */
protected $LogFilePath; // 日志路径
protected $SaveLogFile; // 是否记录日志
private $_MESSAGE; // 日志消息队列
private $_GRADATION = 0; // 日志编序

/* 特殊功能安全码判断 */
protected function Advance()
{
if(($this->SafelyNumber <> $this->SetSafelyNumber)
|| ($this->SafelyNumber == null)
|| ($this->SafelyNumber == ''))
return true;
{
return false;
}
}

/* 从结果集中取得列信息并作为对象返回 */
public function ExtractionRowInfo()
{
if($this->Advance()) //如果安全码不正确,则退出
{
$this->LogRecorder('Safely Number Error' ,1);
die('Insecurity : Use invalidation for Insecurity Item');
}

if($this->_InsecQry == false) // 如果结果资源不存在
{
$this->LogRecorder('Error : Not Use Query() Get Reorder' ,1);
die('Find not recorder convene');
}

$this->LogRecorder('Extraction row Info method is mysql_fetch_field' ,0);

while($Tmp=@mysql_fetch_field($this->_InsecQry))
{
$Row[] = $Tmp;
}

if($Row)
{
$this->LogRecorder('Extraction Row Info Object Array Sueeccd ' ,0);
} else {
$this->LogRecorder('Extraction Row Info Object Array Lost ',1);
}

$this->ResultFree($this->_InsecQry);
return $Row;
}

/* 返回字符集的名称 */
public function Encoding()
{
if($this->Advance())
{
$this->LogRecorder('Safely Number Error' ,1);
die('Insecurity : Use invalidation for Insecurity Item');
}
$charset = mysql_client_encoding($this->_Connect);
if($charset)
{
return $charset;
} else {
return false;
}
}
/* MySql 信息 */
public function MySqlInfo($name)
{
if($this->Advance())
{
$this->LogRecorder('Safely Number Error' ,1);
die('Insecurity : Use invalidation for Insecurity Item');
}
switch ($name)
{
case "CLIENT":
$_return = @mysql_get_client_info();
break;
case "SERVER":
$_return = @mysql_get_server_info($this->_Connect);
break;
case "HOST":
$_return = @mysql_get_host_info($this->_Connect);
break;
case "PROTO":
$_return = @mysql_get_proto_info($this->_Connect);
break;
case "STATE":
$_return = @mysql_stat($this->_Connect);
case "PROCES":
$_return = @mysql_list_processes($this->_Connect);
case "THREAD":
$_return = @mysql_thread_id($this->_Connect);

case 0:
$_return = @mysql_get_client_info();
break;
case 1:
$_return = @mysql_get_server_info($this->_Connect);
break;
case 2:
$_return = @mysql_get_host_info($this->_Connect);
break;
case 3:
$_return = @mysql_get_proto_info($this->_Connect);
break;
case 4:
$_return = @mysql_stat($this->_Connect);
case 5:
$_return = @mysql_list_processes($this->_Connect);
case 6:
$_return = @mysql_thread_id($this->_Connect);
default:
return false;
}
if($_return == false)
{
return false;
} else {
return $_return;
}
}

/* MySql是否正在服务 */
public function ping()
{
$_Ping = @mysql_ping($this->_Connect);
if($_Ping)
{
return true;
} else {
return false;
}
}
/* 列出所有数据库 */
public function ListDataBase()
{
if($this->Advance())
{
$this->LogRecorder('Safely Number Error' ,1);
die('Insecurity : Use invalidation for Insecurity Item');
}

$_List = @mysql_list_dbs($this->_Connect);
if($_List)
{
while ($row = @mysql_fetch_object($_List))
{
$_LD[] = $row->Database;
}
return $_LD;
} else {
return false;
}
}
/* 释放内存 */
private function ResultFree($Result)
{
$_FreeMemory = @mysql_free_result($Result);

if($_FreeMemory)
{
$this->LogRecorder('free memory Succeed ',0);
} else {
$this->LogRecorder('free memory Lost ',1);
}
}

/* 得出一个错误日志 */
public function GetLogRecorder()
{
if($this->_MESSAGE == '')
{
return 'null';
} else {
return $this->_MESSAGE;
}
}

/* 错误日志记录 */
protected function LogRecorder($Message,$State)
{
$this->_GRADATION = (int)$this->_GRADATION + 1;
$Order = $this->_GRADATION . '、';
if($this->SaveLogFile)
{
$_IsExist = file_exists($this->LogFilePath);
if($_IsExist == false)
{
$f = @fopen($this->LogFilePath,'x');
@fclose($f);
}

if(is_writable($this->LogFilePath))
{
$Handle = fopen($this->LogFilePath,'a');
flock($Handle,LOCK_EX);
if($State == 0)
{
fputs($Handle,'Succeed: ' . $Message . ' -> ' . date('y-m-d H:i:s A') . ' ');
} else {
fputs($Handle,'Lost: ' . $Message . ' -> ' . date('y-m-d H:i:s A') . ' ');
}
fclose($Handle);
}
}

if($State == 1)
{
$this->_MESSAGE = $this->_MESSAGE . '<BR><font color=red>' . $Order . $Message . ' -> ' . date('y-m-d h:i:s A') . '</font>';
} else if($State == 0) {
$this->_MESSAGE = $this->_MESSAGE . '<BR><font color=blue>' . $Order . $Message . " -> " . date('y-m-d h:i:s A') . '</font>';
} else if(is_null($State) || ($State == '') || is_numeric($State) == false) {
$this->_MESSAGE = $this->_MESSAGE . '<BR>' . $Order . $Message . ' -> ' . date('y-m-d h:i:s A') . '</font>';
}
}
}
?>
请使用 Zend Studio 查看或者使用该代码注释,会更容易上手。
此PHP数据库操作引擎,使用了大量的PHP操作MYSQL的基本功能及高级功能。
对PHP开发网站快捷起到非常大的作用。期待高手改进该代码!