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

<?php
class 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值