Smudger
Smudger

Reputation: 10781

catch mysql pdo error

I am trying to get to grips with pdo. I have the below function:

  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); 

how do I know if the query ran correctly? if it was not successful I would like a certain action to be performed but not sure how to 'catch' the error.

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

Thanks in advance,

Upvotes: 1

Views: 192

Answers (3)

Mihai Iorga
Mihai Iorga

Reputation: 39704

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);
}

Upvotes: 2

AdamLazaruso
AdamLazaruso

Reputation: 572

A simply try/catch block would work:


    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;
    }

Or if you just want a true/false value returned rather than a specific 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;
    }

Upvotes: 1

René Höhle
René Höhle

Reputation: 27295

There is a function for PDO this function retrieve the error information. Perhaps it helps.

PDO errorinfo

Upvotes: 0

Related Questions