Is there any problem in checking PHP PDO connection this manner?

Is there any problem in checking PHP PDO connection this manner?

Is this way reliable?

function pdo_mysql()
{
$mysql_string = "xxxxxxxxxxx";$mysql_user = "xxxxxxxxxxx";
$mysql_pass = "xxxxxxxxxxx"; try {$pdo_mysql = new PDO( $mysql_string,$mysql_user, $mysql_pass );$pdo_mysql->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$pdo_mysql->setAttribute( PDO::ATTR_EMULATE_PREPARES, false ); return true; } catch( PDOException$ex )
{
log_action( "pdo_mysql", $ex->getCode() . ": " .$ex->getMessage() );
return false;
}
return false;

}


and then checking the return like this:

if( $pdo_mysql = pdo_mysql() )  1 Answer I'm not quite sure I see the purpose of this function. It essentially checks if a PDO connection is possible. It does not actually return a connection. In addition to that, it has hard coded credentials, thus killing all flexibility. Also, there's no evident reason why you made it MySQL specific. None of your options used are MySQL specific. Since a boolean is returned, if($pdo_mysql = pdo_mysql() ) is redundant too:

if (pdo_mysql()) is sufficient (unless you plan on using the true/false \$pdo_mysql outside of the if/else block).

You should pass the credentials into the function instead of hard coding them. Once you've done that though, you've kind of removed any need for the function.

Personally, I don't see a purpose for this function. Just make the connection without this function. If you want to keep it in some kind of centralized place, just keep in it a simple bootstrap file, or even a simple bootstrapping class.

I've been vague on basically everything in this post, so if you want more detail, let me know :).

Also, I might have missed the point of your function. Is your end goal to connect to a MySQL server, or to check if you could connect to a MySQL server?

• thank you. I do see what you mean, and agree. Would be better to return the actual connection. But I have been researching all day and have since found, what I believe is, a better way. Oct 5 '12 at 21:17