PDO : if no error, continue

Hi there everyone!

I know how to throw an error if the db connection fails but I’d like to know how to say if ($connection was successful)

Connection:

$dsnServ = "mysql:host=$server_dbhost;dbname=$server_dbname;".$servdbport;
$optionsServ = [
	PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
	PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
	PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
	 $pdoServ = new PDO($dsnServ, $server_dbuser, $server_dbpass, $optionsServ);
} catch (\PDOException $e2) {
	 $notice[] = array(
		"lvl"=>"danger", 
		"msg"=>"Unable to connect to database."
	);
}

Would I just say

if($pdoServ != NULL)

Or is there a more acceptable way of doing this?

thanks for your time!

PDO always throws an exception on connection failure, no matter which error mode you set. Hence you don’t need a test for when the connection is successful.

Also, the golden rule for catching exceptions is that you catch an exception if (and only if) you can handle the problem that caused the exception.

Thanks for your help!

I just don’t know how to progress with an SQL statement only if the connection is successful. I don’t want the script to stop or display anything if it’s failed, I just don’t want the following statements to be performed if it’s a failed connection. will

if($pdoServ != NULL)

or

if(!$try)

? I just not sure what to wrap the statements in so that they only run on successful connection.

I think I’ve solved it:

if(ISSET($pdoServ)){
					echo 'conn successful<br>';
				}else{
					echo 'conn failed: '.$e2.'<br>';
				}
			}
			UNSET($invaldb);
			UNSET($pdoServ);

My script is continuing to run when I provide incorrect credentials and the connection fails.

You need to handle the error either in the catch block or use set_exemption_handler to handle it. Most basic way in the catch is to use die with a simple connection error message. I use the latter for my custom error handling.

<?php declare(strict_types=1);

define('DB_TYPE', 'mysql'); // Database Type
define('DB_NAME', 'pdo_bumpstart'); // Database Name
define('DB_USER', 'FAKEUSER'); // Database Username
define('DB_PASSWORD', 'FAKE_PASSWORD'); // Database Password
define('DB_HOST', 'localhost'); // Database Hostname
define('DB_CHARSET', 'utf8'); // Database Charset
$dsn = DB_TYPE . ":host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
$opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
];
try
{
    $pdo = new PDO($dsn, DB_USER, DB_PASSWORD, $opt);
}
catch(PDOException $e)
{
    die('DB ERROR') ;

}

echo 'I will not run with a bad connection';

Example with generic set_exception_handler

<?php declare(strict_types=1);

set_exception_handler("custom_exception");

function custom_exception($exception)
{
    echo 'Fatal Error!';
}

define('DB_TYPE', 'mysql'); // Database Type
define('DB_NAME', 'pdo_bumpstart'); // Database Name
define('DB_USER', 'FAKEUSER'); // Database Username
define('DB_PASSWORD', 'FAKE_PASSWORD'); // Database Password
define('DB_HOST', 'localhost'); // Database Hostname
define('DB_CHARSET', 'utf8'); // Database Charset
$dsn = DB_TYPE . ":host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
$opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
];

    $pdo = new PDO($dsn, DB_USER, DB_PASSWORD, $opt);

echo 'I will not run with a bad connection';

My issue is that I need the script to continue running if the connection fails. Further along, I’ll check to see if the connection produced the desired content and if not, I use another system to glean some of the info.

So it’s good that my script is continuing to run, I don’t want the whole script to fail with the connection.

How about telling what you are actually doing that it doesn’t matter if the DB connection fails.

Sure, if that’s necessary to receive help on the issue, it’s a web panel that allows users to monitor and control multiple gameservers, some of which utilize a database. The cron script needs to contact every gameserver to ensure it’s running. The cron’s server loop connects to the gameserver and the gameserver’s db, if it has one, then grabs the information needed before looping to the next gameserver. If one gameserver fails or it’s db is not reachable, then a warning gets placed in the notifications array and the script needs to move on to the next gameserver.

The script can’t stop because one gameserver’s db was unreachable of all subsequent gameserver data will be lost.

Still not seeing the problem. Just wrap the entire process for a given database into a try/catch block…

$databases = ['db1','db2','db3'];
$masterResults = [];
foreach($databases as $database) {
    try {
        $results = process_database($database);
        $masterResults = array_merge($masterResults,$results);
    } 
    catch(PDOException $e)
    {
        /// Oops $database messed up, oh well
    }
}
// No need for any try/catch blocks here, let the calling routine deal with them
function process_database($database)
{
    $pdo = new PDO ...
    $results = $pdo->execute ...
    $pdo = null; // close connection
    return $results;
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.