Correction status:Uncorrected
Teacher's comments:
用接口定义常量,类来完成接口连接数据库方法,类外部执行数据库操作指令并打印结果:
<?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));
点击 "运行实例" 按钮查看在线实例
页面上打印数据库查询结果: