![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<?php class Connect { public $host = "localhost"; //服务器地址 public $uid = "root"; //数据库的用户名 public $pwd = "123"; //数据库的密 //执行SQL语句,返回相应结果的函数 //$sql是要执行的SQL语句 //$type是SQL语句的类型,0代表增删改,1代表查询 //$db代表要操作的数据库 //返回json数据 public function PDO_json($sql,$type=1,$db="mydb") { try { $dsn = "mysql:dbname=mydb;host=localhost"; $pdo = new PDO($dsn,$this->uid,$this->pwd); } catch(Exception $e) { echo "连接失败".$e->getMessage(); } $st = $pdo->prepare($sql); $result = $st->execute(); if($type==1) { $att = $st->fetchAll(PDO::FETCH_ASSOC); return json_encode($att); } else { if($result) { return "OK"; } else { return "NO"; } } } //返回二维数组 public function PDO_array($sql,$type=1,$db="mydb") { try { $dsn = "mysql:dbname=mydb;host=localhost"; $pdo = new PDO($dsn,$this->uid,$this->pwd); } catch(Exception $e) { echo "连接失败".$e->getMessage(); } $st = $pdo->prepare($sql); $result = $st->execute(); if($type==1) { return $st->fetchAll(PDO::FETCH_NUM); } else { //如果是其他语句,返回true或false if($result) { return "OK"; } else { return "NO"; } } } //返回字符串 public function PDO_string($sql,$type=1,$db="mydb") { try { $dsn = "mysql:dbname=mydb;host=localhost"; $pdo = new PDO($dsn,$this->uid,$this->pwd); } catch(Exception $e) { echo "连接失败".$e->getMessage(); } $st = $pdo->prepare($sql); $result = $st->execute(); if($type==1) { return $st->fetchColumn(); } else { if($result) { return "OK"; } else { return "NO"; } } } } ?>