Home > php教程 > php手册 > 我的 DataBase类

我的 DataBase类

WBOY
Release: 2016-06-13 09:53:07
Original
1167 people have browsed it




我的 DataBase类
解决方法




/**

* 数据库配置类

*/



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;

请大家多多指教!

[ ]


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]

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template