1

我正在努力掌握 pdo。我有以下功能:

  function get_editusers($db)  
  {    
    $result = $db->query("SELECT firstname, middlename,surname,fullname,gender, birthdate,homelanguage,department,employeetype,employeestatus,idnumber FROM Persons where employeeid='$employeeid'"); 
    return $result; 
  } 
  $useredit = get_editusers($db); 

我如何知道查询是否正确运行?如果不成功,我希望执行某个操作,但不确定如何“捕获”错误。

if($useredit="failed"){ action if failed} else { action if true}

提前致谢,

4

3 回答 3

2
function get_editusers($db){    
    try {
         $result = $db->query("SELECT firstname, middlename,surname,fullname,gender, birthdate,homelanguage,department,employeetype,employeestatus,idnumber FROM Persons where employeeid='$employeeid'"); 
         return $result; 
    } catch(PDOException $ex) {
         return $ex;
    }
}

$result = get_editusers($db);
if(isset($result->errorInfo)){
    die($result);
}
于 2012-10-09T13:15:28.567 回答
1

一个简单的 try/catch 块就可以了:


    try{
        $result = $db - > query("SELECT firstname, middlename,surname,fullname,gender, birthdate,homelanguage,department,employeetype,employeestatus,idnumber FROM Persons where employeeid='$employeeid'");
    return $result;
    }
    catch(PDOException $exception){
        return $exception;
    }

或者,如果您只想返回真/假值而不是特定异常:


    $result = $db -> query("SELECT firstname, middlename,surname,fullname,gender, birthdate,homelanguage,department,employeetype,employeestatus,idnumber FROM Persons where employeeid='$employeeid'");

    if (!$result){
        return false;
    }
    else{
        return true;
    }
于 2012-10-09T13:19:46.100 回答
0

PDO有一个函数,这个函数检索错误信息。也许它有帮助。

PDO 错误信息

于 2012-10-09T13:15:35.953 回答