<?php
/**
* Created by PhpStorm.
* User: XiaoSheng
* Date: 2019/05/10
* Time: 11:14
*/
class Sql
{
public $host;
public $port;
public $user;
public $pass;
public $dbname;
public $charset;
//初始化操作
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'] ?? '';
$this->dbname = $info['dbname'] ?? 'laravel54';
$this->charset = $info['charset'] ?? 'utf8';
$this->sql_connect();
$this->sql_charset();
}
public $link;
public function sql_connect()
{
$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);
}
}
public 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)
{
//执行sql
$res = $this->link->query($sql);
if(!$res){
die('Sql Error(' . $this->link->error . ')' . $this->link->error);
}
//没有问题,执行结束
return $res;
}
// 读方法
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 users";
$res = $s->sql_query($sql);
echo '<pre>';
//var_dump($res);
//写入测试
$sql = "delete from comments limit 1";
$res = $s->sql_exec($sql);
var_dump($res);
PHP连接mysql操作
最新推荐文章于 2021-05-14 18:02:10 发布