I wrote a new database class using PDO. I' struggling with a problem though. I usually return an object, so I can work with it. So when a query failed, I simply return $this
. I have a method called wasSuccessful()
that I use to make sure the query didn't fail.
$result = $database->query(...);
if ($result->wasSuccessful()) {
// do code
}
However, what do I do, when the method returns false
? For example:
...
if (!$this->tableExists($table)) return false;
When this happens, PDO tells me that I can't run functions on a boolean value. How do I tackle this in the best possible way?
Thanks very much in advance!
Rather than relying on the return values of functions, you should use exceptions. Something like this simple example should give you the idea:
In your class:
class MyClass {
public function query($sql, ...$params) {
if (!$this->tableExists($table)) {
throw new \Exception("the table doesn't exist");
return false;
}
}
}
Then in your code:
try {
$result = $database->query(...);
// do stuff with $result, knowing it's ok
} catch (\Exception $e) {
echo "here's our error handling routine";
echo $e->getMessage();
}
In more complex projects it might be desirable to create your own exception classes. As well, you can use try
/catch
within your class, and throw
exceptions from PDO to the higher-level code. For example:
class MyClass {
public function query($sql, ...$params) {
if (!$this->tableExists($table)) {
throw new \Exception("the table doesn't exist");
return false;
}
try {
//do something with the PDO object that might throw an exception
} catch (\PDOException $e) {
// just take this existing exception and throw it to the next catch block
throw $e;
return false;
}
}
}