[英]php: PDO exception handling
I have two PHP files DBConnector.php 我有两个PHP文件DBConnector.php
<?php
class DBConnector {
const DB_STRING = 'mysql:host=localhost;dbname=test';
const DB_USER = 'test';
const DB_PASSWORD = 'qwerty';
private $connection;
function __construct() {
$this->connection = new PDO(self::DB_STRING, self::DB_USER, self::DB_PASSWORD);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
function register_user($user_type, $login, $password, $email, $phone) {
$insert_user_sql = "insert into users (login, password, email, rating, phones, user_type)
values (:login, password(:password), :email, 0, :phone, :user_type)";
$sth = $this->connection->prepare($insert_user_sql);
$sth->execute(array(':login' => $login,
':password' => $password,
':email' => $email,
':phone' => $phone,
':user_type' => $user_type));
}
}
?>
and application.php 和application.php
<?php
require "DBConnector.php";
require "UserType.php";
try {
$db = new DBConnector();
$db->register_user(UserType::OWNER, "test", "test", "test@gmail.com", "+111111111111");
} catch (Exception $e) {
echo "Error occured " + $e->getMessage();
}
?>
If the "insert into users" in DBConnector->register_user generates PDO exception, I can't catch it in my application.php. 如果DBConnector-> register_user中的“插入用户”生成PDO异常,则无法在application.php中捕获它。 Please, help me, what I'm doing wrong. 请帮帮我,我做错了。
I found the problem. 我发现了问题。 The problem was in "plus" symbol, besides "." 问题出在“”之外,还有“加号”符号。 in echo command. 在echo命令中。 So "0" was printed, instead "Error occured..." 因此打印了“ 0”,而是“发生错误...”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.