<?php class DBDA { public $host = "localhost"; public $uid = "root"; public $pwd = "20982239"; //执行sql语句,返回相应的结果函数 //$sql是要执行的sql语句 //$type是sql语句的类型,0代表增删改,1代表查询 //$db代表要操作的数据库 public function Query($sql,$type=1,$db="mydb") { $conn = new MySQLi($this->host,$this->uid,$this->pwd,$db); !mysqli_connect_error() or die ("连接失败!"); $result = $conn->query($sql); if($type==1) { //如果是查询语句返回结果集的二维数组 return $result->fetch_all(); } else { //如果是其他语句,返回true或false return $result; } } //Ajax调用返回字符串 public function StrQuery($sql,$type=1,$db="mydb") { //造连接对象 $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"; } } } //Ajax调用返回JSON public function JsonQuery($sql,$type=1,$db="mydb") { //定义数据源 $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);//json_encode将一个关联数组转化成json数据 } else { if($st) { return "OK"; } else { return "NO"; } } } else { echo "执行失败!"; } } } ?>