HOME
DOMAIN
WEB HOST
AUTO Site
VPS SERVER
CLOUD HOST
SERVER
HK HOST
AGENT
SERVICE
/** * 数据库配置类 */ class DBConfig { public static $HOST = 'localhost'; public static $USERNAME = 'root'; public static $PASSWORD = 'root'; public static $DATABASE = 'shopping'; public static $CHARSET = 'utf8'; } ?>
/** * 数据库操作类 */ class DataBase{ private $connection; /** * 构造方法 * @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."'"); } /** * 析构方法 * @access public */ public function __destruct(){ mysql_close($this>connection); } /** * 执行SQL查询语句 * @access private * @param string $p_sql 查询命令 * @return 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; } /** * 执行SQL语句 * @access public * @param string $p_sql 需要执行的SQL,可以为INSERT,SELECT,UPDATE或DELETE * @return 如果SQL是SELECT,返回记录集,如果SQL是INSERT,返回新记录ID,如果SQL是UPDATE或DELETE,返回所影响的行数 */ 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;