【发布时间】:2020-09-01 19:49:28
【问题描述】:
我有三个类,每个类在连接到我的数据库时处理不同的功能。
类 1,名称为 ConnectDB(),处理 MySqli() 连接;名称为 MessageOut() 的类 2 通过 $_SESSION['message'] 键向用户 UI 提供错误和成功消息,名称为 WebApp() 的类 3 使用 MySqli 连接从数据库中检索数据并将其传递给 UI。
这与我通常进行数据库连接、收集和显示的方式不同。通常我只是在三个文件中创建了很多函数,并在需要时调用它们。但是我的网站变得越来越大,越来越复杂,所以我正在重新组织一切。
我目前的问题是当我在我的第三堂课中创建数据库连接时,它没有抛出我编程的错误。
class ConnectDB {
//Connecting to database
public function connect() {
//connecting to mysql
@$conn = new mysqli(DB_HOST, DB_USERRW, DB_PASSWRW, DB_DBASE);
// check validity of database connection
if (mysqli_connect_errno()) {
return false;
exit();
}
// select the database to use
return $conn;
}
}
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
class WebApp {
protected $db;
function __construct(){
$this->connector = new ConnectDB();
$this->messager = new MessageOut();
try {
$this->db = $this->connector->connect();
if(!$this->db) {
throw new Exception(' Database connection is currently unavailable.');
}
} catch (Exception $e) {
mysqli_report(MYSQLI_REPORT_OFF);
$errors = array();
$message = $e->getMessage();
//populate array with message and divert output to error class functions
array_push($errors, $message);
$this->messager->erroutput($errors);
}
}
public function selectIdata() {
//select data
try {
$query = "SELECT *
FROM thetable";
$stmt = $this->db->prepare($query);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($idata);
$result = [];
if ($stmt->num_rows > 0) {
while ($stmt->fetch()) {
$result[] = $idata;
}
return $result;
} else {
return false;
}
} catch (Exception $e) {
mysqli_report(MYSQLI_REPORT_OFF);
$errors = array();
$message = $e->getMessage();
//populate array with message and divert output to error class functions
array_push($errors, $message);
$this->messager->erroutput($errors);
}
}
}
我将我的本地主机定义的密码更改为错误的密码并加载了文件,但在我的第一堂课的第 10 行给出了错误,即使错误被抑制了。这个想法是在使用之前检查连接。
如何在我的第三堂课中抛出错误,给我“数据库连接当前不可用”。消息?
编辑
所以我重新评估了我所做的并在我的第三堂课的constructor 中设置了一个try-catch 块,但我知道我收到了一个错误:Fatal error: Uncaught Error: Call to a member function prepare() on null in 第 41 行的第三堂课,其中使用了 db 连接。
【问题讨论】:
-
为什么你有所有这些try-catch,你为什么抛出异常?
-
这永远不会是真的
if(!$this->db) -
我在
WebApp()类的__constructor中检查数据库连接是否为假,如果是则抛出没有可用连接的错误。我注意到我必须以某种方式将异常从ConnectDB()类冒泡到WebApp()类才能捕获它。 -
为什么
if(!$this->db)永远不会是真的?属性$this->db设置为$this->connector->connect()方法的返回值。如果返回值为假,那么!$this->db不会为真,即$this->db === false? -
你杀死你的脚本,所以它永远不会返回 false。
标签: php oop mysqli try-catch throw