user1121487
user1121487

Reputation: 2680

PDO connection try catch include

I'm new to PDO and I wanna do it right from the beginning - I'm going to replace my old mysql_ functions on a site.

Have I got it right?:

Should I put the connection code in a try/catch and save it to a file, and include it on top of the page. Then put the queries in try/catch as well.

Or:

Should I put the connection code in a file and include it in the in the top of the try/catch statement above the query?

ver1:

include('pdo.php'); // try/catch in file

try { 

    $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
    $stmt->execute(array('id' => $id));

    while($row = $stmt->fetch()) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

ver2:

try {
    include('pdo.php'); // no try/catch in file

    $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
    $stmt->execute(array('id' => $id));

    while($row = $stmt->fetch()) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

Or should I put the try/catch in both places?

Upvotes: 1

Views: 1267

Answers (1)

Ugo Méda
Ugo Méda

Reputation: 1215

You should do both and even more :

  • Set an error handler that displays a message to the user and stops the PHP (see set_error_handler)
  • When you initiate the connexion, add a try/catch and throw an error if you catch an exception. Your website won't run without database connection i guess.
  • Do a try/catch around your queries to recover gracefully from error (when you can)

Upvotes: 1

Related Questions