最模板 - 外贸网站建设,外贸网站模板

最模板

当前位置: 首页 > 建站教程 > php教程 >

我的 DataBase类

时间:2014-06-09 16:40来源: 作者: 点击: 次
/** *数据库配置类 */ class DBConfig { public static $HOST = localhost ; public static $USERNAME = root ; public static $PASSWORD = root ; public static $DATABASE = shopping ; public static $CHARSET = utf8 ; } ? /** *数据库操作类 */ class
  1. /** 
  2. * 数据库配置类 
  3. */ 
  4. class DBConfig 
  5. { 
  6. public static $HOST = 'localhost'; 
  7. public static $USERNAME = 'root'; 
  8. public static $PASSWORD = 'root'; 
  9. public static $DATABASE = 'shopping'; 
  10. public static $CHARSET = 'utf8'; 
  11. } 
  12. ?> 

 

  1. /** 
  2.  
  3. * 数据库操作类 
  4.  
  5. */ 
  6. class DataBase{ 
  7. private $connection; 
  8. /** 
  9. * 构造方法 
  10.  
  11. * @access public 
  12.  
  13. */ 
  14. public function __construct(){ 
  15.  
  16. $CONFIG = require(dirname(__FILE__).'/DBConfig.class.php'); 
  17.  
  18. $this>connection = mysql_connect(DBConfig::$HOST,DBConfig::$USERNAME,DBConfig::$PASSWORD); 
  19.  
  20. mysql_select_db(DBConfig::$DATABASE); 
  21.  
  22. mysql_query("SET NAMES '".DBConfig::$CHARSET."'"); 
  23.  
  24. } 
  25. /** 
  26.  
  27. * 析构方法 
  28.  
  29. * @access public 
  30.  
  31. */ 
  32. public function __destruct(){ 
  33. mysql_close($this>connection); 
  34. } 
  35.  
  36. /** 
  37. * 执行SQL查询语句 
  38.  
  39. * @access private 
  40.  
  41. * @param string $p_sql 查询命令 
  42.  
  43. * @return array 记录集,无记录返回空数组 
  44.  
  45. */ 
  46.  
  47. private function query($p_sql){ 
  48.  
  49. $dataTemp = mysql_query($p_sql,$this>connection); 
  50.  
  51. $data = array(); 
  52.  
  53. $dataItem = 0; 
  54.  
  55. while ($rows = mysql_fetch_assoc($dataTemp)) { 
  56.  
  57. $data[$dataItem] = $rows; 
  58.  
  59. $dataItem++; 
  60. } 
  61. return $data; 
  62. } 
  63. /** 
  64. * 执行SQL语句 
  65. * @access public 
  66. * @param string $p_sql 需要执行的SQL,可以为INSERT,SELECT,UPDATE或DELETE 
  67. * @return 如果SQL是SELECT,返回记录集,如果SQL是INSERT,返回新记录ID,如果SQL是UPDATE或DELETE,返回所影响的行数 
  68. */ 
  69. public function execute($p_sql){ 
  70. $controlr = strtoupper(substr($p_sql,0,6)); 
  71. switch ($controlr) { 
  72. case 'INSERT': 
  73. mysql_query($p_sql,$this>connection); 
  74. $result = mysql_insert_id($this>connection); 
  75. break; 
  76. case 'SELECT': 
  77. $result = $this>query($p_sql,$this>connection); 
  78. break; 
  79. default: 
  80. mysql_query($p_sql,$this>connection); 
  81. $result = mysql_affected_rows($this>connection); 
  82. break; 
  83. } 
  84. return $result; 
  85. } 
  86. } 
  87. ?> 

调用很简单:

  1. $sql = '.....'; // 可以是任何增删改查的语句 
  2. $db = new DataBase(); 
  3. $rs = $db>execute($sql); 
  4. $db = null; 

(责任编辑:admin)
------分隔线----------------------------
栏目列表
推荐内容