PHP MySQL单例、函数封装

./config.php

设定数据库连线信息

<?php
/**
 * 返回数据库连线的关联数组
 *
 * @return array $arr 关联数组
 */
function getConfig()
{
    $arr = [
        'db_host' => 'localhost',
        'db_port' => '3306',
        'db_user' => 'root',
        'db_pwd' => '123456',
        'db_name' => 'shop',
        'db_charset' => 'utf8'
    ];
    return $arr;
}

 ./mysql.php

使用单例,常用函数封装

<?php
class MySQL
{
    private $host;      // 主机地址
    private $port;      // 端口号
    private $user;      // 用户名
    private $pwd;       // 密码
    private $name;      // 数据库名
    private $charset;   // 字符集
    private $link;      // 连接对象

    // 实现单例
    private static $instance;
    // 建构式private,确保外部无法实例化
    private function __construct()
    {
        $this->initParam();
        $this->initConnect();
    }
    /**
     * 外部调用获取实例
     *
     * @return MySQL $instance 返回该类的实例
     */
    public static function getInstance()
    {
        if (!self::$instance)
            self::$instance = new self();
        return self::$instance;
    }
    /**
     * 初始化参数
     *
     * @return void
     */
    private function initParam()
    {
        require_once './config.php';
        $config = getConfig();
        $this->host = $config['db_host'];
        $this->port = $config['db_port'];
        $this->user = $config['db_user'];
        $this->pwd = $config['db_pwd'];
        $this->name = $config['db_name'];
        $this->charset = $config['db_charset'];
    }
    /**
     * 连接数据库,设定编码方式
     *
     * @return void
     */
    private function initConnect()
    {
        $this->link = mysqli_connect($this->host, $this->user, $this->pwd, $this->name, $this->port);
        // 检查连线
        if (mysqli_connect_error()) {
            echo '数据库连线失败<br>';
            echo '错误信息:' . mysqli_connect_error() . '<br>';
            echo '错误码:' . mysqli_connect_errno() . '<br>';
            exit; // 终止脚本,页面不变
        }
        mysqli_set_charset($this->link, $this->charset);
    }
    /**
     * 只查询、执行SQL语句
     *
     * @param string $sql
     * @return mysqli_result|true 查询返回mysqli_result,增删改返回true
     */
    private function execute($sql)
    {
        $result = mysqli_query($this->link, $sql);
        // 若查找失败会返回false,印出并终止
        if (!$result) {
            echo 'SQL语句执行失败<br>';
            echo '错误信息:' . mysqli_error($this->link) . '<br>';
            echo '错误码:' . mysqli_errno($this->link) . '<br>';
            echo '错误的SQL语句:' . $sql . '<br>';
            exit;
        }
        return $result;
    }
    /**
     * 外部调用增、删、改,判别$key是否符合
     *
     * @param string $sql
     * @return true 若$result=false,会印出错误信息并终止,不会返回false
     */
    public function exec($sql)
    {
        // 关键词
        $key = substr($sql, 0, 6);
        if (in_array($key, array('insert', 'update', 'delete')))
            return $this->execute($sql);
        else {
            echo '非法访问<br>';
            exit;
        }
    }
    /**
     * 对关键词$key的过滤,不能使用未定义的关键词来执行sql语句
     *
     * @param string $sql
     * @return mysqli_result 限制了select才可以通过,只会返回$result结果
     */
    private function query($sql)
    {
        // 会返回mysqli_result物件的不止select,不能用in_array()
        if (substr($sql, 0, 6) === 'select')
            // 只会返回mysqli_result,若是false会在execute()时终止
            return $this->execute($sql);
        else {
            echo '非法访问<br>';
            exit;
        }
    }
    /**
     * 查询所有数据
     *
     * @param string $sql
     * @param string $type 想要的型别 assoc|num|both
     * @return array 返回二维数组/空数组
     */
    public function queryAll($sql, $type = 'assoc')
    {
        $result = $this->query($sql);
        $type = $this->getType($type);
        return mysqli_fetch_all($result, $type);
    }
    /**
     * 查找一笔数据
     *
     * @param string $sql
     * @param string $type 想要的型别 assoc|num|both
     * @return array 返回符合的第一笔数据/空数组
     */
    public function queryOne($sql, $type = 'assoc')
    {
        $result = $this->query($sql);
        $type = $this->getType($type);
        return mysqli_fetch_array($result, $type);
    }
    // 其他工具
    private function getType($type)
    {
        switch ($type) {
            case 'num':
                return  MYSQLI_NUM;
            case 'both':
                return  MYSQLI_BOTH;
            default:
                return  MYSQLI_ASSOC;
        }
    }
}

// 使用方法...

使用方法

// 使用方法...

// 建立实例
$db = MySQL::getInstance();

// 增、删、改,失败显示错误信息,成功返回true
$result = $db->exec({$sql语句});

// 查询一条数据,失败显示错误信息,成功返回一维数组(数据内容)
$list = $db->queryOne({$sql语句}, {$可选型别});
echo '<pre>';
var_dump($result);

// 查询所有数据,失败显示错误信息,成功返回二维数组
$list = $db->queryAll({$sql语句}, {$可选型别});
echo '<pre>';
var_dump($result);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值