php 连接数据库

本文介绍了一个使用PHP实现的MySQL数据库连接类,该类采用单例模式,并提供了基本的数据库操作方法,如执行增删改查等SQL语句。通过实例演示了如何连接数据库并展示比赛列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php

/**
 * Created by PhpStorm.
 * User: qxb-810
 * Date: 2017/1/10
 * Time: 10:20
 */
//类名,也习惯上(推荐)使用跟文件名相似的名字
//定义一个mysql连接类,该类可以连接mysql数据库
//并实现其单例模式
//该类的功能还能够完成如下基本mysql操作:
//执行普通的增删改非返回结果集的语句
//执行select语句并可以返回3种类型的数据:
//多行结果(二维数组),单行结果(一维数组)
//单行单列(单个数据)
class MySQLDB {
    public $host;
    public $port;
    public $username;
    public $password;
    public $charset;
    public $dbname;

    //连接结果(资源)
    private static $link;

    private $resource;

    public static function getInstance($config){
        if(!isset(self::$link)){
            self::$link = new self($config);
        }
        return self::$link;
    }

    //构造函数:禁止new
    private function __construct($config){
        //初始化数据
        $this->host = isset($config['host']) ? $config['host'] : 'localhost';
        $this->port = isset($config['port']) ? $config['port'] : '3306';
        $this->username = isset($config['username']) ? $config['username'] : 'root';
        $this->password = isset($config['password']) ? $config['password'] : '';
        $this->charset = isset($config['charset']) ? $config['charset'] : 'utf8';
        $this->dbname = isset($config['dbname']) ? $config['dbname'] : '';

        //连接数据库
        $this->connect();
        //设定连接编码
        $this->setCharset($this->charset);
        //选定数据库
        $this->selectDb($this->dbname);
    }
    //禁止克隆
    private function __clone(){}
    //这里进行连接
    public function connect(){
        $this->resource = mysqli_connect("$this->host:$this->port", "$this->username","$this->password") or die("连接数据库失败!");
    }
    public function setCharset($charset){
        mysqli_set_charset($this->resource, $charset);
    }
    public function selectDb($dbname){
        mysqli_select_db($this->resource, $dbname);
    }

    /**
     * 功能:执行最基本(任何)sql语句
     * 返回:如果失败直接结束,如果成功,返回执行结果
     */
    public function query($sql){
        if(!$result = mysqli_query($this->resource, $sql))
        {
            echo ("<br />执行失败。");
            echo "<br />失败的sql语句为:" . $sql;
            echo "<br />出错信息为:" . mysqli_error();
            echo "<br />错误代号为:" . mysqli_errno();
            die();
        }
        return $result;
    }
    /**
     * 功能:执行select语句,返回2维数组
     * 参数:$sql 字符串类型 select语句
     */
    public function getAll($sql){
        $result = $this->query($sql);
        $arr = array();    //空数组
        while( $rec = mysqli_fetch_assoc( $result )){
            $arr[] = $rec;//这样就形成二维数组
        }
        return $arr;
    }
    //返回一行数据(作为一维数组)
    public function getRow($sql){
        $result = $this->query($sql);
        //$rec = array();
        if( $rec2 = mysqli_fetch_assoc( $result )){//返回下标为字段名的数组
            //如果fetch出来有数据(也就是取得了一行数据),结果自然是数组
            return $rec2;
        }
        return false;
    }
    //返回一个数据(select语句的第一行第一列)
    //比如常见的:select count(*) as c from XXX where ...
    public function getOne($sql){
        $result = $this->query($sql);
        $rec = mysqli_fetch_row($result);//返回下标为数字的数组,且下标一定是0,1,2, 3.....
        //如果没有数据,返回false
        if($result === false){
            return false;
        }
        return $rec[0];    //该数组的第一项。

    }

}

<?php
require './MySQLDB.class.php';
/**
 * Created by PhpStorm.
 * User: qxb-810
 * Date: 2017/1/10
 * Time: 10:14
 */
 //比赛列表
header('Content-type: text/html; charset=utf-8');
//连接数据库
$mysqlConfig = array('password'=>'root', 'dbname'=>'php34');
$dao = MySQLDB::getInstance($mysqlConfig);
$sql = "SELECT
            t1.t_name AS t1_name,
            m.t1_score,
            m.t2_score,
            t2.t_name AS t2_name,
            FROM_UNIXTIME(m.m_time) AS m_time
        FROM
            `match` AS m
        LEFT JOIN team AS t1 ON m.t1_id = t1.t_id
        LEFT JOIN team AS t2 ON m.t2_id = t2.t_id";
$matchList =  $dao->getAll($sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>比赛列表</title>
</head>
<body>
<table>
    <tr>
        <th>球队一</th><th>比分</th><th>球队二</th><th>时间</th>
    </tr>
    <?php foreach($matchList as $key=>$val): ?>
        <tr><td><?php echo $val['t1_name'] ?></td><td><?php echo $val['t1_score'].':'.$val['t2_score'] ?></td><td><?php echo $val['t2_name'] ?></td><td><?php echo $val['m_time'] ?></td></tr>
    <?php endforeach; ?>
</table>


</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值