Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO Connection Test

Tags:

php

mysql

pdo

I am writing an installer for one of my apps and I would like to be able to test some default database settings.

Is this possible using PDO to test valid and invalid database connections?

I have the following code:

try{             $dbh = new pdo('mysql:host=127.0.0.1:3308;dbname=axpdb','admin','1234');             die(json_encode(array('outcome' => true)));         }catch(PDOException $ex){             die(json_encode(array(                 'outcome' => false,                 'message' => 'Unable to connect'             )));         } 

The problem I am having is that the script trys to connect until the script execution time of 60 seconds runs out instead of saying it cannot connect to the db.

Thanks

like image 618
Lee Avatar asked Jun 07 '11 09:06

Lee


People also ask

What is PDO connection?

The PDO represents a connection between PHP and a database server. The PDOStatement represents a prepared statement and, after the statement is executed, an associated result set. The PDOException represents an error raised by PDO.

Do you have to close PDO connection?

The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning null to the variable that holds the object.


1 Answers

you need to set the error mode when connection to the database:

try{     $dbh = new pdo( 'mysql:host=127.0.0.1:3308;dbname=axpdb',                     'admin',                     '1234',                     array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));     die(json_encode(array('outcome' => true))); } catch(PDOException $ex){     die(json_encode(array('outcome' => false, 'message' => 'Unable to connect'))); } 

for more infos see the following links:

Using MySQL with PDO

Errors and error handling

like image 143
Sascha Galley Avatar answered Sep 23 '22 06:09

Sascha Galley