//连接数据库
class dbda{
//定义数据库连接定义参数
public $host = 'localhost'; //一般都是localhost
public $user = 'root'; //访问数据库时的身份
public $pwd = ''; //数据库密码
public $database = 'gps'; //所使用的数据库的名字
public $charset = 'utf8'; //这是字符集
public $db = null; //数据库连接对象
public $res = null; //结果集
//初始化数据
function __construct($configArr = array()){
//通过三元运算符进行比较
$this ->host = isset($configArr['host']) ? $configArr['host']:'localhost';
$this ->user = isset($configArr['user']) ? $configArr['user']:'root';
$this ->pwd = isset($configArr['pwd']) ? $configArr['pwd']:'';
$this ->database = isset($configArr['database']) ? $configArr['database']:'gps';
$this ->charset = isset($configArr['charset']) ? $configArr['charset']:'utf8';
//连接数据库
$this -> connect();
}
//连接数据库
function connect(){
$this -> db = new MySQLi($this->host,$this->user,$this->pwd,$this->database);
!mysqli_connect_error() or die ('连接失败');
$this->db->query('set names utf8');
}
//执行sql语句的方法
function query($sql){
$res = $this->db->query($sql);
if(!$res){
echo ("<br />执行失败。");
echo "<br />失败的sql语句为:" . $sql;
echo "<br />出错信息为:" . mysql_error($this->db);
echo "<br />错误代号为:" . mysql_errno($this->db);
die();
}
return $res;
}
//返回结果集转成二维数组
function getAll($sql){
$res = $this->query($sql);
return $res -> fetch_all();
}
//返回字符串
//返回josn
//返回关联数组
function getAssoc($sql){
$result = $this->query($sql);
$arr=array();
while($row = $result->fetch_assoc()){
$arr[$row['uid']] = $row;
}
return $arr;
}
}
//实例化
$aaaa = new dbda();
$sql ='select * from login';
$att =$aaaa->getAssoc($sql);
var_dump($att);
php引用
function __autoload($className){
require $className.".php";
}
//require "DBDA.php";
$dbda = dbda::getDb();
var_dump($dbda->getAll('select * from login'));