Php pdo database connection

Before working with database you should create connection with database other wise your queries will be not work or fail, if you are using mysql database there are 3 type of connection we can create:
1. Using mysql Database Connection in PHP
2. Using mysqli database connection in php
3. PDO (PHP Data Object)

So Here we are writing code of how to create mysql database connection with PHP PDO.

  1. One most important reason PDO is working with 12 different type of database, where MySQLi is working with MySQL databases only.
  2. So, in future if you want to switch your project to use another database, Then PDO makes the process easy. You only have to change the connection string and a few queries but with MySQLi, you will need to rewrite the entire code and queries.
  3. Both are object-oriented, but MySQLi also offers a procedural API.
  4. Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.

How to create PHP PDO database connection Code

Here we write simple PDO connection code for use just copy it. You need only change database name, host, username and paswword.

<?php
$HostName = 'localhost';
$DataBase = 'test';
$UserName = 'root';
$PassWord = '';
try {
    $DBH = new PDO("mysql:host=$HostName;dbname=$DataBase", $UserName, $PassWord);
    $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e){
    echo $e->getMessage;
}
?>

How to use PDO Connection With Queries

// SELECT QUERY USING PHP PDO
$STH = $DBH->query('SELECT * from users');
$STH->setFetchMode(PDO::FETCH_ASSOC); 
while($row = $STH->fetch()) {
    echo $row['id'] . " ";
    echo $row['username'] . "<br>";
}

About Author

My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.