<?php
class Sql{
private $host;
private $port;
private $user;
private $pass;
private $dbname;
private $charset;
private $link;
public $affected_rows;
public $num_rows;
public function __construct(array $info =array()){
$this->host = $info['host'] ?? 'localhost';
$this->port = $info['port'] ?? 3306;
$this->user = $info['user'] ?? 'root';
$this->pass = $info['pass'] ?? 'chz';
$this->dbname = $info['dbname'] ?? 'demo';
$this->charset = $info['charset'] ?? 'utf8';
$this->sql_conn();
$this->sql_charset();
}
//连接数据库
private function sql_conn(){
$this->link = @new mysqli($this->host,$this->user,$this->pass,$this->dbname,$this->port);
if($this->link->connect_error){
die('Connect Error ('.$this->link->connect_errno.')'.$this->link->connect_error);
}
}
//设置字符集
private function sql_charset(){
$sql = "set names {$this->charset}";
$res = $this->link->query($sql);
if(!$res){
die('Charset Error('.$this->link->errno.')'.$this->link->error);
}
}
//数据库写操作
public function sql_exec($sql){
$res = $this->link->query($sql);
if(!$res){
die('Sql Error('.$this->link->errno.')'.$this->link->error);
}
$this->affected_rows = $this->link->affected_rows;
return $res;
}
//获取数据表中的最后一个id
public function get_sql_last_id(){
return $this->link->insert_id;
}
//数据库查询操作
public function sql_query($sql,$all = false){
$res = $this->link->query($sql);
if(!$res){
die('Sql Error('.$this->link->errno.')'.$this->link->error);
}
if($all){
return $res->fetch_all(MYSQLI_ASSOC);
}else{
return $res->fetch_assoc();
}
}
}
$s = new Sql();
$sql = 'select * from students';
$res = $s->sql_query($sql,true);
echo '<pre>';
print_r($res);
//删除最后两条记录
$sql = 'delete from students order by id desc limit 2';
$res = $s->sql_exec($sql,true);
var_dump($res);
//新增两条记录
$sql = "insert into students values(null,'cjk',13)";
$res = $s->sql_exec($sql,true);
$sql = "insert into students values(null,'ghk',12)";
$res = $s->sql_exec($sql,true);
//获取数据表中的最后一个id
echo '<br>'.$s->get_sql_last_id();