【发布时间】:2019-03-13 14:40:09
【问题描述】:
我正在学习如何使用 PDO 通过 php 连接到 mySQL 数据库的教程,我正在尝试确定我的连接是否良好。这是我的代码,但我不知道如何检查我是否已连接。
如何更新以下代码,使其返回“已连接”与“未连接”消息?
<?php
class Database
{
private static $dbName = 'benrud_carsData' ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'benrud_read5th';
private static $dbUserPassword = 'XXXXXXX';
private static $cont = null;
public function __construct() {
die('Init function is not allowed');
}
public static function connect()
{
// One connection through whole application
if ( null == self::$cont )
{
try
{
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect()
{
self::$cont = null;
}
}
?>
【问题讨论】:
-
您想返回什么信息?看起来
connect()当前返回了连接。如果你返回了一条消息,它就不会再返回连接了,这是不好的。 -
您应该查看
Singlton模式,您已经实现了大约一半。更适合 DB 的是多个单例模式。碰巧我在 GitHub 和 Composer 上有它。 -
@esqew 可能重复的答案很有趣。根据我的经验,无论是否设置了 PDO::ATTR_ERRMODE,构造新 PDO 时的连接失败都会抛出 PDOException。