How to connect database using PHP and PDO

Connecting database using PDO’s in php

In any case, it takes three arguments to connect to mysqli using PDO in PHP:

1. a string specifying the type of database (mysql:), the hostname of the server
(host=hostname;), and the name of the database (dbname=database)
2. the MySQL username you want PHP to use
3. the MySQL password for that username

$pdo = new PDO('mysql:host=yourhostnamehere;dbname=userdatabasenamehre',
'usernamehere',
'passwordhere');

Now let’s connect t database using try and catch

try{
$pdo = new PDO("mysql:host=localhost;dbname=testdb;","username","password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, ERMODE_EXCEPTION);
echo $output =  "connection established successfully";
}
catch(PDOException $e)
{
echo $output = "ERROR ".$e->getMessage()."in".$e->getFile()."on".$e->getLine();
}

As you can see, this code is a try … catch statement. In the try block at the top,
we attempt to connect to the database using new PDO. If this succeeds, we store
the resulting PDO object in $pdo so that we can work with our new database
connection. If the connection is successful, the $output variable is set to a
message that will be displayed later.
Importantly, inside a try … catch statement, any code after an exception has
been thrown will not get executed. In this case, if connecting to the database
throws an exception (maybe the password is wrong or the server isn’t
responding), the $output variable will never get set to “Database connection
established”.
If our database connection attempt fails, PHP will throw a PDOException, which
is the type of exception that new PDO throws. Our catch block, therefore, says that
it will catch a PDOException (and store it in a variable named $e). Inside that
block, we set the variable $output to contain a message about what went wrong.
However, this error message isn’t particularly useful. All it tells us is that PDO
could not connect to the database server. It would be better to have some
information about why that was—for example, because the username and
password were invalid.

Leave a Reply

Your email address will not be published.

%d bloggers like this: