Home  >  Article  >  Backend Development  >  My DataBase Class_PHP Tutorial

My DataBase Class_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:51:51718browse




我的 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]

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/632535.htmlTechArticle我的 DataBase类 解决方法 /*** Database configuration class*/ class DBConfig { public static $HOST = 'localhost'; public static $USERNAME = 'root'; public static $PASSWORD = 'root';...
Statement:
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