Am I connecting the bank with PDO in the correct way?

2

There are several ways to connect to the database, but I have opted for PDO. Am I doing it right?

date_default_timezone_set('America/Sao_Paulo');

$pdo = new PDO('mysql:host=127.0.0.1;dbname=experiments','root');

if ($pdo) {
    echo "Banco de dados conectado!";
}
elseif ($pdo) {
    echo "Banco de dados não conectado.";
}
    
asked by anonymous 17.07.2014 / 02:34

1 answer

7

It is in the path, the syntax for connection to the database with pdo is given as follows:

$pdo = new PDO(dsn, user, password, options);

Since dsn is the connection string with the bank (yours is correct), user is the user, password is the password and options which is an array containing other options that is optional.

I give the suggestion that instead of using the if..else control structure, use the try..catch exception handling structure because it tries to execute the code within the first block and in case there is an error or exception occurrence the code in the catch block is automatically executed. In the following way:

try{

$pdo = new PDO(dsn, user, password, options);

}catch(PDOException $e){

exit("Erro na conexão com a base de dados");

}

So, if an error occurs, the script execution will be finished and the message "Error in connection with the database" will be displayed, otherwise it will not display any messages.

For more details on using the "try..catch..finally" or other exception handling framework, visit the php manual.

I hope I have helped and good luck;)

    
17.07.2014 / 03:06