<?php class DBDA { public $host = "localhost"; //服务器地址 public $uid = "root"; //数据库的用户名 public $pwd = ""; //数据库的密码 //执行SQL语句,返回相应结果的函数 //$sql是要执行的SQL语句 //$type是SQL语句的类型,0代表增删改,1代表查询 //$db代表要操作的数据库 public function Query($sql,$type=1,$db="xm_youxiang") { //造连接对象 $conn = new MySQLi($this->host,$this->uid,$this->pwd,$db); //判断连接是否成功 !mysqli_connect_error() or die("连接失败!"); //执行SQL语句 $result = $conn->query($sql); //判断SQL语句类型 if($type==1) { //如果是查询语句返回结果集的二维数组 return $result->fetch_all(); } else { //如果是其他语句,返回true或false return $result; } } //Ajax调用返回JSON public function JsonQuery($sql,$type=1,$db="xm_youxiang") { //定义数据源 $dsn = "mysql:dbname={$db};host={$this->host}"; //造pdo对象 $pdo = new PDO($dsn,"{$this->uid}","{$this->pwd}"); //准备执行SQL语句 $st = $pdo->prepare($sql); //执行预处理语句 if($st->execute()) { if($type==1) { $attr = $st->fetchAll(PDO::FETCH_ASSOC); return json_encode($attr); } else { if($st) { return "OK"; } else { return "NO"; } } } else { echo "执行失败!"; } } //Ajax调用返回字符串 public function StrQuery($sql,$type=1,$db="xm_youxiang") { //造连接对象 $conn = new MySQLi($this->host,$this->uid,$this->pwd,$db); //判断连接是否成功 !mysqli_connect_error() or die("连接失败!"); //执行SQL语句 $result = $conn->query($sql); //判断SQL语句类型 if($type==1) { $attr = $result->fetch_all(); $str = ""; //如果是查询语句返回字符串 for($i=0;$i<count($attr);$i++) { for($j=0;$j<count($attr[$i]);$j++) { $str = $str.$attr[$i][$j]; $str = $str."^"; } $str = substr($str,0,strlen($str)-1); $str = $str."|"; } $str = substr($str,0,strlen($str)-1); return $str; } else { //如果是其他语句,返回true或false if($result) { return "OK"; } else { return "NO"; } } } }