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.

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

How to use PDO Connection With Queries

$STH = $DBH->query('SELECT * from users');
while($row = $STH->fetch()) {
    echo $row['id'] . " ";
    echo $row['username'] . "<br>";

Leave a Reply

Related Posts: You may like

How to remove whitespace from string using php

Remove All Special Characters From String PHP

Redirecting HTTP to HTTPS with PHP

Convert Base64 string to an image file


Crypto Currency

PHPKIDA provides free online the best real-time crypto market price, news, predictions, index with graphs & historical data for 2000+ coins including bitcoin, ethereum, & altcoins from major cryptocurrency exchanges.

Visite Tool

Icon Generator

PHPKIDA provides free online icon generator. Our icon generator help you to edit, modify, resize and customize icon for your website and applications. Convert to a shap you like add icon border, you can change icon border color, border size, background color, icon shadow, icons color, icon size in your own way and save it as a png image.

Visite Tool

Youtube Video Downloader

PHPKIDA provides Free online YouTube video downloader to download YouTube videos quickly in MP4, 3GP, and more. Search your video and free fast download youtube videos.

Visite Tool

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.