Tags

, , ,

How to pinpoint the PDO error in PHP7? Here is a code sample that may come to your help.
First, we get a “pdo.connect.php” file. Next, we will use that file to elegantly catch our errors!

interface InterfaceConnect {
public function connect();
}

class Connect
{
protected $dsn;
protected $user;
protected $pass;
}

class Connection extends Connect implements InterfaceConnect
{
public function connect() {

$this->dsn = "mysql:host=localhost;dbname=test";
$this->user = "root";
$this->pass = "*******";

$connect = new \PDO($this->dsn, $this->user, $this->pass);
return $connect;

}
}

Next in any file we can include that connection file and find the error elegantly!
Please follow the comments to understand what is happening inside.

require_once 'pdo-connect.php';

class ErrorFinding
{
public function findError() {

try {
$con = new Connection;
$connect = $con->connect();
if($connect){

// to find the exact error we make it intentionally vulnerable
// originally the table name was subjects
$sql = "select * from subject";

$rows = $connect->query($sql);

// to pinpoint the error we need the PDO connection object
$error = $connect->errorInfo();
echo $error[2]; //Table 'test.subject' doesn't exist

while ($row = $rows->fetch()) {
if($row['category_id'] == 1){
$name[] .= htmlspecialchars($row['name']);
}

}
return $name;

}

} catch (Exception $ex) {
echo $ex->getMessage();
}
}

}

$error = new ErrorFinding;

foreach ($error->findError() as $value) {
echo $value . "
";
}

The output in the browser looks like this:

Table ‘test.subject’ doesn’t exist