sql增、删、改、查基础封装类

mac2022-06-30  65

<?phpclass DB{ private $link;//私有变量 /** * 构造方法 * DB constructor. * @param $dbname * @param $username * @param $pwd * @param string $host */ public function __construct($dbname,$username,$pwd,$host='127.0.0.1') { $this->link=new PDO("mysql:host:$host:dbname=$dbname","$username","$pwd"); $this->link->exec('set names utf8'); $this->link->setAttribute(PDO::ATTR_ERRMODE,1); } /** * 获取一条数据 * @param $where  平衡例条件 * @param $table  要查询的数据表 * @return int   返回值 */ public function getOne($where="1",$table) { if (empty($table)) { return "没有输入数据表"; die(); } $sql="select * from new where $where"; $stmt=$this->link->query($sql); return $stmt->fetch(2); } /** * 查询多条数据 * @param string $where 要查询的数据 * @param $table 要查询的数据表 * @return string 返回值 */ public function getAll($where="1",$table) { if (empty($table)) { return "没有输入数据表"; die(); } $sql="select * from new where $where"; $stmt=$this->link->query($sql); return $stmt->fetchAll(2); } /** * 删除 * @param $table 要删除的数据表 * @param $where 删除的条件 * @return int|string 返回值 */ public function del($table,$where){ if (count($where)==0 || empty($table)){ return "没有删除条件"; } $str=""; foreach ($where as $k=>$v) { $str.="`$k`='$v'"; } $sql="delete from `$table` where $str"; return $this->link->exec($sql); } /** * 添加一条语句 * @param $table 要添加的数据表 * @param $array 添加的数据 * @return int|string 返回值 */ public function add($table,$array) { if(empty($table)){ return "没有插入的数据表"; } if(count($array)==0){ return "没有要插入的数据"; die(); } $filed="";//用于字段 $val="";//用于存放数据 foreach ($array as $k=>$v){ $filed.="`$k`,"; $val.="'$v',"; } $filed=substr($filed,0,-1); $val=substr($val,0,-1); $sql="insert into `$table`($filed) VALUES ($val)"; return $this->link->exec($sql); } /** * 修改的方法 * @param $table 要修改的数据表 * @param $array 修改的数据 * @param $where 修改的条件 * @return int|string 返回值 */ public function save($table,$array,$where=""){ if(empty($table)){ return "没有修改的数据表"; } if(count($array)==0){ return "没有要修改的数据"; die(); } if(empty($where)){ return "没有要修改的条件"; die(); } $str=""; foreach ($array as $k=>$v){ $str.="`$k`='$v',"; } $str=substr($str,0,-1); $sql="update `$table` set $str where $where"; return $this->link->exec($sql); } public function __destruct() { // TODO: Implement __destruct() method. $this->link="";//关闭连接 }}?>

转载于:https://www.cnblogs.com/liujunyue/p/11320761.html

相关资源:SQLHelper 类封装了增删改查
最新回复(0)