Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using IF conditional statements with PDO

I have a connection to a database that looks something like this:

$data_source_name = "mysql:host=$db_host;dbname=$db_name";

$database_connection = new PDO($data_source_name, $db_username, $db_password);

The execution looks something like this:

$stmt= $database_connection->prepare($sql);

$stmt->execute([$name, $email]);

I’m trying to set up a condition like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if ( database connection fails ) {
   // error handling
}

But this code doesn’t work.

if ( !$database_connection ) {
     // error handling
} else {
    $stmt= $database_connection->prepare($sql);
    $stmt->execute([$name, $email]);
}

This if construct works in MySQL and MySQLi, but not PDO. Any guidance appreciated. Thanks.

>Solution :

new PDO raises an exception if the connection fails. Use an exception handler:

try {
    $database_connection = new PDO($data_source_name, $db_username, $db_password);
} catch (PDOException $e) {
    // error handling
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading