<?php
//封装一个数据库操作的工具类
class mysql{
//属性
private $host;
private $user;
private $pass;
private $dbname;
private $port;
private $link;
//构造方法
public function __construct($host="localhost",$user="root",$pass="980613",$dbname="studyphp",$port="3306"){
$this->host = $host;
//如果没输入参数就调用默认值
$this->user = $user;
$this->pass= $pass ;
$this->dbname = $dbname ;
$this->port = $port;
//用户在实例化对象时 自动连接 所以调用mysql_connect方法
$this->mysql_connect($this->host,$this->user,$this->pass,$this->dbname,$this->port);
$this->setNames();
}
//利用 mysqli类连接认证
public function mysql_connect($host,$user,$pass,$dbname,$port){
$this->link = new mysqli($host,$user,$pass,$dbname,$port);
//返回一个 mysqli对象 后面经常需要这个对象调用方法 所以把对象保存为类的属性
//判断是否连接成功 连接失败返回false
if(!$this->link){
echo '('.$this->link->connect_errno.')'.$this->link->error;;
}
}
//封装一个执行sql语句 并且进行判断的函数 减少冗余
public function queryAndJduge($sql){
$res = $this->link->query($sql);//mysqli对象的query方法 执行成功返回true
if(!$res){
echo '('.$this->link->connect_errno.')'.$this->link->error;
//利用mysqli的connect_error属性 与connect_error属性
}else{
return $res;
}
}
//设置字符集 同样在构造方法中运行此代码 降低用户操作复杂度
public function setNames($names='utf8'){
$sql = "set names {$names}";
$this->queryAndJduge($sql);
}
//增删改功能 本质都是执行sql语句
//新增一个受影响的行数属性
public $affected_rows;
public function goQuery($sql){
$res = $this->queryAndJduge($sql);
$this->affected_rows = $this->link->affected_rows;
//affected_rows 返回上面增改删操作受影响的行数
return $res;
}
//封装一个获取当前自增长id 的方法
public function sql_last_id(){
return $this->link->insert_id;
//利用mysqli对象的insert_id 返回上面通过插入操作之后 最后一个自增长的id 删改操作不会调用这个函数
}
//查询功能 有查询多句以及查询一句
//新增属性 $num_rows 代表查询出的行数
public $num_rows;
public function goSelect($sql,$all=false){
//执行查询语句 返回的不是boolean值而是一个mysqli_result结果集对象
$res=$this->queryAndJduge($sql);
$this->num_rows=$res->num_rows;
if($all){
return $res->fetch_all(MYSQLI_ASSOC);
//利用mysqli_resulti结果集对象的fetch_all方法 返回所有数组 并且利用类常量 让返回的数组里 表的字段作为属性
//使用的是拓展库mysqli_assoc常量 作为参数 让返回的多为数组的第二维数组的索引为数据库字段
}else{
return $res->fetch_assoc();
}
}
}
?>