Php PDO异常未触发/可能的范围相关?
由于预计mysql_query将被弃用PHP 5.5.0,我一直在开发一个类来处理我的所有DB查询:Php PDO异常未触发/可能的范围相关?,php,pdo,Php,Pdo,由于预计mysql_query将被弃用PHP 5.5.0,我一直在开发一个类来处理我的所有DB查询: class DataBaseClass { //.....some other function and variables declared here.... function GetConnection() { try { $this->conn = new PDO("mysql:host=" . DB_HOST . ";dbna
class DataBaseClass {
//.....some other function and variables declared here....
function GetConnection() {
try {
$this->conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
return $this->conn;
}
function Query($str_sql, $arr_parameters = array()) {
try {
$this->str_mysql_error = $this->int_num_rows = $this->int_num_affected_rows = $this->int_mysql_insert_id = '';
if (count($arr_parameters) > 0) {
$obj_result = $this->conn->prepare($str_sql);
$obj_result->execute($arr_parameters);
} else {
$obj_result = $this->conn->query($str_sql);
}
}
catch(PDOException $e) {
$this->str_mysql_error = $e->getMessage() . $str_sql;
}
}
}
然后我有另一个类来创建新用户:
class AddNewUser {
//.....some other function and variables declared here....
function InsertUser() {
$str_sql = "INSERT INTO (uname, name, email, pass, user_regdate, theme) VALUES )";
$_SESSION['db_connection']->Query($str_sql, '');
}
}
现在,在我的主要用户创建页面上,我有:
$_SESSION['db_connection'] = new DataBaseClass;
//Reason I used $_SESSION to store my DB object, is so that it can be accessible everywhere.
//Did not want to use "global" everywhere. Not sure if this is he best way???
$cls_new_user = new AddNewUser ();
$cls_new_user->InsertUser(); //Does not raise PDOExecption although SQL cleary wrong inside this method
if ( $_SESSION['db_connection']->str_mysql_error) {
//show error in error div
}
$str_sql = "SELECT some wrong SQL statment";
$_SESSION['db_connection']->Query($str_sql); // This does raise PDOExecption
if ( $_SESSION['db_connection']->str_mysql_error) {
//show error in error div
}
我不知道为什么DB类函数“Query”在从另一个类调用时不会在明显错误的SQL上引发异常。但从主页代码调用的同一函数(不在函数/类内部)会引发异常错误
此外,“InsertUser”函数不会在数据库中执行/插入任何内容,即使SQL是正确的
它可能与作用域相关,或者我试图通过将DB对象放入$\u会话来强制其全局作用域
我走错方向了吗?采用类路径封装所有我的DB调用的原因是为了避免将来出现任何弃用问题—只需更新类。这样做函数
function Query($str_sql, $arr_parameters = array()) {
$stmt = $this->conn->prepare($str_sql);
$stmt->execute($arr_parameters);
}
我很确定会抛出异常
唯一的问题是捕获异常,而不是抛出异常。它可能是由名称空间而不是范围引起的。可以肯定的是,您可以始终使用斜杠在所有PDO调用前加上前缀:
\PDO::FETCH_ASSOC
\PDOException
等等。你怎么知道没有引发异常?我肯定它确实引发了异常,但你捕获了它-并且你没有在事后检查
$this->str_mysql\u错误。
对不起,我忘了在检查var$this->str_mysql\u错误的地方添加代码。我现在已经添加了它。第一个if语句$\u SESSION['db\u connection']->str\u mysql\u error为空。第二个有错误并触发我的错误divHmm的显示-您是否记录/调试以检查是否达到catch块,str_mysql_error变量是否为空,还有其他原因?好的,在两天后,我发现了问题<代码>添加新用户->插入器()方法,我调用如下查询函数:$\u SESSION['db\u connection']->query($str\u sql')代码>假设第二个参数为空字符串,则会导致方法参数默认为空数组。正如他们所说,假设是一切之母。。。。但由于我在主页调用中省略了第二个参数,所以它默认为空数组。只有当我在$obj_result->execute($arr_参数)
周围放置if
时,我才意识到它不会触发catch块