我的 DataBase类
解决方法
/**
* Database configuration class
*/
class DBConfig
{
public static $HOST = 'localhost';
public static $USERNAME = 'root';
public static $PASSWORD = 'root';
public static $DATABASE = 'shopping';
public static $CHARSET = 'utf8';
}
?>
复制代码
/**
* Database operation class
*/
class DataBase{
private $connection;
/**
*Construction method
* @access public
*/
public function __construct(){
$CONFIG = require(dirname(__FILE__).'/DBConfig.class.php');
$this>connection = mysql_connect(DBConfig::$HOST,DBConfig::$USERNAME,DBConfig::$PASSWORD);
mysql_select_db(DBConfig::$DATABASE);
mysql_query("SET NAMES '".DBConfig::$CHARSET."'");
}
/**
* Destruction method
* @access public
*/
public function __destruct(){
mysql_close($this>connection);
}
/**
* Execute SQL query statement
* @access private
* @param string $p_sql query command
* @return array record set, if no record returns an empty array
*/
private function query($p_sql){
$dataTemp = mysql_query($p_sql,$this>connection);
$data = array();
$dataItem = 0;
while ($rows = mysql_fetch_assoc($dataTemp)) {
$data[$dataItem] = $rows;
$dataItem++;
}
return $data;
}
/**
* Execute SQL statement
* @access public
* @param string $p_sql The SQL to be executed, which can be INSERT, SELECT, UPDATE or DELETE
* @return If SQL is SELECT, return the record set. If SQL is INSERT, return the new record ID. If SQL is UPDATE or DELETE, return the number of affected rows
*/
public function execute($p_sql){
$controlr = strtoupper(substr($p_sql,0,6));
switch ($controlr) {
case 'INSERT':
mysql_query($p_sql,$this>connection);
$result = mysql_insert_id($this>connection);
break;
case 'SELECT':
$result = $this>query($p_sql,$this>connection);
break;
default:
mysql_query($p_sql,$this>connection);
$result = mysql_affected_rows($this>connection);
break;
}
return $result;
}
}
?>
复制代码调用很简单:
$sql = '.....'; // 可以是任何增删改查的语句
$db = new DataBase();
$rs = $db>execute($sql);
$db = null;
请大家多多指教!
[ ]
D8888D回贴内容
看看呢 ~~ [img]http://www.phpchina.com/bbs/images/smilies/default/shy.gif[/img][img]http://www.phpchina.com/bbs/images/smilies/default/shy.gif[/img]