Heim  >  Artikel  >  Backend-Entwicklung  >  我的 DataBase类_PHP教程

我的 DataBase类_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:51:51716Durchsuche




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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/632535.htmlTechArticle我的 DataBase类 解决方法 /** * 数据库配置类 */ class DBConfig { public static $HOST = 'localhost'; public static $USERNAME = 'root'; public static $PASSWORD = 'root';...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn