Am I connecting the bank with PDO the right way?

Asked

Viewed 101 times

2

There are several ways to connect to the database, but I opted for PDO. I’m doing it the right way?

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.";
}

1 answer

7


It is in the way, the syntax for connection to the Pdo database is given as follows:

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

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

I suggest that instead of using the if.. Lse control structure, use the Try exception handling structure.. catch, as it tries to execute the code within the first block and if there is error or exceptions automatically the code in the catch block is executed. As follows:

try{

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

}catch(PDOException $e){

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

}

Thus, in case of error the execution of the script will be terminated and the message "Error in connection with the database" will be shown, otherwise it will not display any message.

For more details on using the "Try. .catch.. Finally" or other exception handling structure, visit the php manual.

I hope I helped and good luck ;)

  • great explanation, thanks for the clarification.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.