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

Leave a Reply

Related Posts: You may like

Extract Total Number of Image And Missing Alt Attribute using php

How to extract Heading tags using PHP from string

How to remove whitespace from string using php

Remove All Special Characters From String PHP

PHPKIDA Offering Free Tools:

INSTA DOWNLOADER

Download Instagram Videos & Photos.

Download Now

CURRENCY CONVERTER

Real Time Currency Converter

Convert Now

ROBOST.TXT GEN.

Robots.txt File Creater

Create Now

HTML MINIFIER

Compress yout HTML Code

Minify Now

CSS MINIFIER

Compress yout CSS Code

Minify Now

JAVASCRIPT MINIFIER

Compress yout JavaScript Code

Minify Now

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.