how does PHP connect to a database

Question

Answers ( 1 )

    0
    2024-01-11T18:05:21+00:00

    PHP can connect to various types of databases, but the most common is MySQL. Below, I'll provide a detailed description and code examples for connecting to a MySQL database using PHP.

    Using MySQLi (MySQL Improved)

    MySQLi is a PHP extension designed to handle the new features of MySQL. There are two ways to use MySQLi: procedural and object-oriented.

    Procedural Approach

    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
    
    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    
    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    echo "Connected successfully";
    

    Object-Oriented Approach

    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
    

    Using PDO (PHP Data Objects)

    PDO is a database access layer providing a uniform method of access to multiple databases.

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

    Choosing Between MySQLi and PDO

    • MySQLi: Offers procedural and object-oriented way. It only works with MySQL databases.
    • PDO: Offers only object-oriented way. It supports 12 different databases.

    Notes

    1. Security: Use prepared statements and parameterized queries to prevent SQL injection.
    2. Database Credentials: The above examples use placeholders for the database credentials. Replace them with your actual database server details, username, and password.
    3. Error Handling: Always implement error handling to catch connection failures or errors.

    Each method has its advantages, and the choice depends on your specific project requirements and personal preference.

Leave an answer