PDOException不触发/可能范围相关?

时间:2013-06-07 13:08:22

标签: php pdo

由于预期mysql_query被弃用PHP 5.5.0,我一直在处理一个类来处理我的所有数据库查询:

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上引发异常。但是从主页面代码(不在函数/类内)调用的相同函数引发和异常错误。

此外,即使SQL正确,“InsertUser”函​​数也不会在DB中执行/插入任何内容。

它是否与范围相关,或者我试图通过将其放在$ _SESSION中来强制实施我的数据库对象的全局范围?

我是以错误的方式来做这件事的吗?将类路由封装所有数据库调用的原因是为了避免将来出现任何弃用问题 - 只需要更新类。

1 个答案:

答案 0 :(得分:0)

以这种方式使你的功能。

 function Query($str_sql, $arr_parameters = array()) {
        $stmt = $this->conn->prepare($str_sql);
        $stmt->execute($arr_parameters);
 }

我很确定会抛出异常

唯一的问题可能是捕捉异常,而不是抛出。它可能是由Namespace引起的,而不是范围引起的。确切地说,您始终可以使用斜杠添加所有PDO调用:

\PDO::FETCH_ASSOC
\PDOException