How to Link MySQL Database to PHP With MySQLi and PDO

When creating dynamic webpages, connecting a PHP application to a MySQL database is a vital step. PDO (PHP Data Objects) and MySQLi (MySQL Improved Extension) are two well-liked ways that PHP provides for creating this connection.

Method to Connect a MySQL Database to PHP Using MySQLi and PDO

Let’s explore the two methods:

Method 1: Connect Using MySQLi

MySQLi supports both object-oriented and procedural approaches.

  1. Object-Oriented Example
    <?php
    
    $servername = “localhost”;
    
    $username   = “root”;
    
    $password   = “”;
    
    $database   = “test_db”;
    
    // Create connection
    
    $conn = new mysqli($servername, $username, $password, $database);
    
    // Check connection
    
    if ($conn->connect_error) {
    
         die(“Connection failed: ” . $conn->connect_error);
    
    }
    
    echo “Connected successfully (MySQLi - OOP)”;
    
    ?>
  1. Procedural Example
    <?php
    
    $servername = “localhost”;
    
    $username   = “root”;
    
    $password   = “”;
    
    $database   = “test_db”;
    
    // Create connection
    
    $conn = mysqli_connect($servername, $username, $password, $database);
    
    // Check connection
    
    if (!$conn) {
    
        die(“Connection failed: ” . mysqli_connect_error());
    
    }
    
    echo “Connected successfully (MySQLi - Procedural)”;
    
    ?>

Method 2: Connect Using PDO

PDO is more flexible as it supports multiple databases (MySQL, PostgreSQL, SQLite, etc.), making it a preferred option for larger projects.

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

try {
$conn = new PDO(“mysql:host=$servername;dbname=$database”, $username, $password);

// Set PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo “Connected successfully (PDO)”;
} catch(PDOException $e) {
echo “Connection failed: ” . $e->getMessage();
}
?>

This way, you can connect a MySQL database to PHP using MySQLi and PDO. Hope you liked our article. For more informative articles, please visit our KB section regularly.

Learn more tutorials about the PHP Script to Test MySQL Database Connectivity.

Popular Posts You May Read

Explore more hosting insights, tips and industry updates.

How to Install ReactJS on Windows (Beginner-Friendly Guide)

How to Install ReactJS on Windows (Beginner-Friendly Guide)

Want to make cool stuff for websites with ReactJS? Great! This guide will help you…

Which SSL Certificate is Good for Your Website?

SSL Certificates are necessary for those sites where a user is supposed to submit highly…

How Do Users Set Up Reseller Accounts in WHM

This post will walk you through the process of creating Reseller Accounts in WHM. Reseller…