You can use MySQLi and PDO to connect MySQL Database in PHP.

MySQL is an Oracle-backed open source relational database management system (RDBMS) based on Structured Query Language (SQL). MySQL runs on virtually all platforms, including LinuxUNIX and Windows. Although it can be used in a wide range of applications, MySQL is most often associated with web applications and online publishing.

MySQL is an important component of an open source enterprise stack called LAMP WAMP. and XAMPP. LAMP is a web development platform that uses Linux as the operating system and WAMP is for Windows also and last is XAMPP is both linux and windows, Apache as the web server, MySQL as the relational database management system and PHP as the object-oriented scripting language.

  • MySQLi (Procedural and Object oriented )
  • PDO

MySQLi

example Procedural:

<?php
$servername = "localhost";
$username = "username"; // in local host you can you "root"
$password = "password"; // in local host you can you " " empty

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

example  Object-Oriented:

<?php
$servername = "localhost";
$username = "username"; // in local host you can you "root"
$password = "password"; // in local host you can you " " empty

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

example PDO:

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
    $conn = new PDO("mysql:host=$servername;dbname=mydatabase", $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();
    }
?>

Close the Connection

example Procedural:

mysqli_close($conn);

example Object Oriented:

$conn->close();

example PDO:

$conn = null;

Note: MySQLi is supported only by MySQL database but the PDO is supported in  12 different database systems;

Leave a Reply

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