Web / PHP

Connecting to MySQL database using php PDO

by Libz
28 Nov 2015 at 11:36hrs | 2336 Views
The following script uses PDO to connect to a MySQL database.

Initialising variables:
     $host_ip = '127.0.0.1';
$db_name = 'my-database';
$db_user = 'my-username';
$db_password ='password';

//data source name (dsn)
$dsn = "mysql:dbname=$db_name;host=$host_ip";

Connecting to the database:
$dbh = new PDO($dsn, $db_user, $password);
In order to catch errors during connecting we can the above code in a try block and then CATCH the error in case there is connection failure.


try{
$dbh = new PDO($dsn, $db_user, $password);
}catch(PDOException $e){
echo 'Error connecting to database :: '.$e->getMessage();
}

Complete code
$host_ip = '127.0.0.1';
$db_name = 'my-database';
$db_user = 'my-username';
$db_password ='password';

//data source name (dsn)
$dsn = "mysql:dbname=$db_name;host=$host_ip";

try{
$dbh = new PDO($dsn, $db_user, $password);
}catch(PDOException $e){
echo 'Error connecting to database :: '.$e->getMessage();
}
 
Source - Libz
More on: MySQL, PDO, PHP



Chat Login

Register | Forgot password