Blogger Information
Blog 49
fans 1
comment 0
visits 45174
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
写一个数据库操作类, 要求用到命名空间, 类继承, 后期绑定访问, 来实现数据表的简单访问(用接口定义常量,类来完成接口连接数据库方法,类外部执行数据库操作指令并打印结果)2019年6月19日20点
Nick的博客
Original
836 people have browsed it

用接口定义常量,类来完成接口连接数据库方法,类外部执行数据库操作指令并打印结果:

实例

<?php
//命名空间
namespace Demo;

use PDO;

if (!interface_exists(__NAMESPACE__.'\iDb')){
    //创建接口,用于保存连接数据库的必要信息
    interface iDb
    {
        //定义常量
        const TYPE = 'mysql';
        const HOST = '127.0.0.1';
        const USER_NAME = 'root';
        const PASSWORD = 'root';
        const DBNAME = 'php';
        //接口中创建一个连接方法,在类中必须实现
        public static function Connection ();
    }
}


class Connection implements namespace\iDb
{
    // 初始化连接参数
    private static $type = iDb::TYPE;
    private static $host = iDb::HOST;
    private static $userName = iDb::USER_NAME;
    private static $password = iDb::PASSWORD;
    private static $dbname = iDb::DBNAME;

    public static function Connection()
    {
        $dsn = self::$type.':host='.self::$host.';dbname='.self::$dbname;
        $user = self::$userName;
        $password = self::$password;
        $pdo = new PDO($dsn,$user,$password);
        //返回pdo对象
        return $pdo;
    }

}
////测试PDO是否拼接完整
//$test = Connection::Connection();
//echo $test->Connection();

//连接数据库
$db = Connection::Connection();

//执行查询
$stmt = $db->prepare('SELECT * FROM staff LIMIT 3');
$stmt->execute();
//在页面打印查询结果
print_r($stmt->fetchAll(PDO::FETCH_ASSOC));

运行实例 »

点击 "运行实例" 按钮查看在线实例


页面上打印数据库查询结果:

利用命名空间,接口,类实现数据库信息查询.png

Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!