mysqli使用封装举例


mysqli函数组使用举例,如mysqli_connect、mysqli_query、mysqli_fetch_array、mysqli_free_result、mysqli_fetch_row、mysqli_affected_rows等等。


正文

mysqli封装类

class mysqliClass
{
    private $DB_HOST = 'localhost';
    private $DB_NAME = 'demo_db';
    private $DB_USER = 'root';
    private $DB_PWD  = 'root';
    private $DB_PORT = 3306;

    protected $con = '';

    /**
     * 构造函数,实例化MYSQL连接
     */
    function __construct()
    {
        $this->con = mysqli_connect($this->DB_HOST, $this->DB_USER, $this->DB_PWD, $this->DB_NAME, $this->DB_PORT);
    }

    /**
     * 获取一行数据
     * @param $sql
     * @return array|null
     */
    public function find($sql)
    {
        $result = mysqli_query($this->con, $sql);
        if ($result) {
            $re = mysqli_fetch_array($result, MYSQLI_ASSOC);
            mysqli_free_result($result);
            
            return $re;
        }
    }

    /**
     * 获取多行数据
     * @param $sql
     * @return array
     */
    public function select($sql)
    {
        $result = mysqli_query($this->con, $sql);
        if ($result) {
            $re = array();
            while ($row = mysqli_fetch_assoc($result))
            {
                $re[] = $row;
            }
            
            return $re;
        }
    }

    /**
     * 获取唯一数据
     * @param $sql
     * @return mixed
     */
    public function field($sql)
    {
        $result = mysqli_query($this->con, $sql);
        if ($result) {
            $row = mysqli_fetch_row($result);
            mysqli_free_result($result);

            if (isset($row[0])) {
                return $row[0];
            }
        }
    }

    /**
     * 执行命令
     * @param $sql
     * @return mixed
     */
    public function query($sql)
    {
        if (mysqli_query($this->con, $sql)) {
            return mysqli_affected_rows($this->con);
        }
    }
}






参考资料

MySQL增强版扩展 http://www.php.net/manual/zh/book.mysqli.php

MySQLi 函数 http://www.w3school.com.cn/php/php_ref_mysqli.asp

MySQLi 函数 http://www.runoob.com/php/php-ref-mysqli.html

mysql与mysqli的异同点 https://www.cnblogs.com/gengyi/p/6544407.html

mysqli 操作数据库 https://www.cnblogs.com/siqi/p/3776577.html

PDO 用法学习 https://www.cnblogs.com/siqi/p/3774871.html


返回