PHP connect to DB

PHP connect to DB

PHP work with a MySQL database using MySQLi (procedural), MySQLi (object-oriented) and PDO (PHP Data Objects)

Difference between MySQLi and PDO

PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases.

Open a Connection to MySQL

To access data in the MySQL database, first of all we need to connect with the server:

Example (PDO)

<?php
$servername = “localhost”;
$username = “root”;
$password = “”;

try {
  $conn = new PDO(“mysql:host=$servername;dbname=shairy”, $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo “Connected successfully”;
} catch(PDOException $e) {
  echo “Connection failed: ” . $e->getMessage();
}
?>

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*