- <?php
- header("Content-Type:text/html;charset=utf-8");
- /**
- *单例模式实现 数据库操作类
- *实例化一次,赋值给静态变量,当再次调用类中方法,只需判断这个变量是否有值即可,无需再实例化类一次
- **/
- class db
- {
- public $conn;
- public static $sql;
- public static $instance=null;
- //构造方法和clone 方法设置为私有属性,防止外部访问
- private function __construct()
- {
- require_once "dbConfig.php";
- $this->conn=mysql_connect($db['host'],$db['user'],$db['password']);
- if (!mysql_select_db($db['database']))
- {
- echo '连接数据库失败';
- }
- mysql_query('set names utf8');
- }
- //private function __clone() {}; //覆盖克隆方法,禁止克隆
- //构造单实例方法
- public static function getInstance()
- {
- if (!(self::$instance instanceof self))
- {
- self::$instance=new db;
- }
- return self::$instance;
- }
- /*
- *数据库查询方法
- *@$table 表名
- *@$data 需要查询的条件数据
- *@$field 需要查询的字段
- */
- public function select($table,$data,$field=null)
- {
- $where='where 1=1';
- if (!empty($data))
- {
- foreach ($data as $key=>$val)
- {
- $where.=' and '.$key.'='."'$val'";
- }
- }
- $fieldstr='';
- if (!empty($field))
- {
- foreach ($field as $k=>$v)
- {
- $fieldstr.=$v.',';
- }
- $fieldstr=rtrim($fieldstr,',');
- }else
- {
- $fieldstr='*';
- }
- /**
- *构造sql语句
- *
- **/
- self::$sql="select {$fieldstr} from {$table} {$where}";
- $res=mysql_query(self::$sql,$this->conn);
- $i=0;
- $result=array();
- while($row=mysql_fetch_assoc($res))
- {
- foreach ($row as $key=>$val)
- {
- $result[$i][$key]=$val;
- }
- $i++;
- }
- return $result;
- }
- /**
- * insert update方法
- **/
- //public function insert(){};
- //public function update(){};
- }
- /**
- *
- *外部调用
- *
- **/
- $db=db::getInstance();
- $arr=$db->select('user',array('username'=>'luowj'),array('username','password'));
- var_dump($arr);
- ?>