PHP数据库通用访问类

<?php
header('Content-type:text/html;charset=utf-8');
require_once 'config.php';
session_start();

class Common
{
 var $dbHost; //定义主机
    var $dbUser; //定义连接用户名
    var $dbPwd;  //定义连接用户密码
    var $dbName; //定义需要查询的数据库名

    //构造函数
    function __construct()
    {
     $this->Init();
    }
   
    //初始化常用变量
    function Init()
    {
     $this->dbhost = $GLOBALS['cfg_dbhost'];
     $this->cfg_dbname = $GLOBALS['cfg_dbname'];
     $this->cfg_dbuser = $GLOBALS['cfg_dbuser'];
     $this->cfg_dbpwd = $GLOBALS['cfg_dbpwd'];
    }
   
    //执行增加、删除、更新SQL语句,返回受影响的行数
    function Execute($query)
    {
     mysql_query($query);
     return mysql_affected_rows();
    }
 
 //遍历查询结果集赋给数组
 function GetArray($query)
 {
    $res = mysql_query($query);
    while($row=mysql_fetch_array($res))
    {
     $return[] = $row;
    }
    return $return;
 }
   
 //打开数据库
 function OpenConn()
 {
  //打开数据库连接
  $this->linkID = $conn = @mysql_connect($this->dbHost,$this->cfg_dbuser,$this->cfg_dbpwd);
  if(!$conn)
  {
   die('连接错误信息: ' . mysql_error());
  }
  //选择表
  $select_table=@mysql_select_db($this->cfg_dbname,$conn);
  if(!$select_table)
  {
   die('数据库错误信息: ' . mysql_error());
  }
  mysql_query('set names utf8'); //防止操作数据库时中文出现乱码
 }
 
 //关闭数据库
 function CloseConn()
 {
  @mysql_close();
 }
}
?>

posted on 2012-05-28 22:22  hesir  阅读(392)  评论(0编辑  收藏  举报

导航