I have read several threads on stackoverflow about these questions:
- Should I use try-catch inside or around the 'query' function?
- Should I use try-catch on each query execution or not?
And, to be honest, I'm not sure I understand the answers - someone says yes, someone says no. So, I want to give practical example of how I do... and if you could give me answers to these two questions.
database.php:
try {
$connection= new PDO(DB_DNS, DB_USER, DB_PASS);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
echo "Error: ".$e->getMessage();
die();
}
user.php:
class User {
public function pronadjiSveUsere() {
global $connection;
$sql= $connection->prepare("SELECT * FROM users");
$result = $sql->execute();
return $result ;
}
public function find_by_id($id=0) {
global $connection;
$sql= $connection->prepare("SELECT * FROM users WHERE id = :id");
$result = $sql->execute(array($id));
return $result->fetch(PDO::FETCH_OBJ);
}
}
As you can see - Class user has two methods. My questions are:
1. Should I use try-catch at all in these cases? 2. If the answer is yes - should I put within methods, for example:
public function find_by_id($id=0) {
try {
global $connection;
$sql= $connection->prepare("SELECT * FROM users WHERE id = :id");
$result = $sql->execute(array($id));
return $result->fetch(PDO::FETCH_OBJ);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
}
or around, whenever I'm use these methods, for example:
try {
user->find_by_id($id);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Thank you in advance!
globalin classes we have properties for that stuff.PDOExceptionNow this will fallback to a standard Exception if not processed in acatch (PDOException $e)but there may be times when you want to differentiate between standard Exceptions and PDOExceptions. So it is better to catch the PDOException. This also makes your code more self documentary.trigger_error. stackoverflow.com/questions/7063053/…globalin a class totally destorys the encapsulation and is not recommended