Write an example to establish MySQL database connection using PHP script?

In PHP, you can establish a MySQL database connection using MySQLi or PDO extensions. The old mysql_connect() function is deprecated and should be avoided. Here are modern approaches to connect to MySQL database.

Using MySQLi (Procedural)

The MySQLi extension provides an interface to access MySQL databases −

<?php
    $servername = "localhost";
    $username = "guest";
    $password = "guest123";
    $database = "testdb";

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

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

Using MySQLi (Object-Oriented)

The object-oriented approach provides better code organization −

<?php
    $servername = "localhost";
    $username = "guest";
    $password = "guest123";
    $database = "testdb";

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

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

Using PDO

PDO (PHP Data Objects) provides a database-agnostic interface −

<?php
    $servername = "localhost";
    $username = "guest";
    $password = "guest123";
    $database = "testdb";

    try {
        $pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
        // Set the PDO error mode to exception
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
    } catch(PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
    
    // Connection closes automatically when script ends
?>

Comparison

Method Object-Oriented Prepared Statements Database Support
MySQLi Procedural No Yes MySQL only
MySQLi OOP Yes Yes MySQL only
PDO Yes Yes Multiple databases

Conclusion

Use MySQLi for MySQL-specific applications and PDO for database-agnostic code. Always use prepared statements for user input to prevent SQL injection attacks.

Updated on: 2026-03-15T07:22:50+05:30

226 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements