PHP连接mysql操作

<?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);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值