Author

PinoyFreeCoder

Published

Thu Apr 11 2024

Type

Free

Download

Not Available

PHPMySQLiPDODatabase ConnectionPHPMySQLiPDODatabase Connection

Share this Source Code

Share This Article

In the vast landscape of web development, PHP remains one of the most popular server-side scripting languages. With its simplicity and versatility, PHP powers numerous dynamic websites and applications, often relying on databases to store and manage data. While MySQL has been a long-standing favorite, there are times when developers need to connect to different databases, such as PostgreSQL or MongoDB. In this guide, we'll explore how to connect to a different database using PHP.

1. Understanding Database Drivers

PHP offers various extensions, often referred to as drivers, to connect to different types of databases. Each driver corresponds to a specific database management system (DBMS). Some commonly used drivers include:

  • MySQLi (MySQL Improved): A modern and improved version of the MySQL extension, providing an object-oriented interface for interacting with MySQL databases.
  • PDO (PHP Data Objects): A database access abstraction layer that offers a unified API for accessing different database systems, including MySQL, PostgreSQL, SQLite, and more.
  • PostgreSQL: A native extension specifically designed to connect to PostgreSQL databases.
  • MongoDB: A driver tailored for interacting with MongoDB, a popular NoSQL database.

2. Installing Necessary Extensions

Before connecting to a different database, ensure that the corresponding PHP extension is installed and enabled on your server. You can typically install extensions using package managers like apt or yum for Linux distributions, or by compiling PHP from source with the desired extensions.

For example, to install the PostgreSQL extension on Ubuntu, you can use the following command:

      
        sudo apt-get install php-pgsql
      
    

Similarly, for MongoDB:

      
        sudo apt-get install php-mongodb
      
    

3. Connecting to the Database

Once you have the necessary extensions installed, connecting to the database is relatively straightforward. Here's a basic example using PDO to connect to a PostgreSQL database:

      
        // This is a PHP file, so make sure it has the .php extension
        $host = 'localhost';
        $dbname = 'my_database';
        $username = 'my_username';
        $password = 'my_password';
        
        try {
            $pdo = new PDO("pgsql:host=$host;dbname=$dbname", $username, $password);
            echo "Connected successfully";
        } catch (PDOException $e) {
            die("Connection failed:".$e->getMessage());
        }
      
    

4. Executing Queries

Once connected, you can execute SQL queries as usual using PDO or the corresponding methods provided by other database-specific extensions. Here's an example of querying a PostgreSQL database using PDO:

      
        // This is a PHP file, so make sure it has the .php extension
        $query = "SELECT * FROM users";
        $stmt = $pdo->query($query);

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo $row['username'] . "
"; }

5. Closing the Connection

It's essential to close the database connection when you're done with it to free up resources. In PDO, you can simply set the database handler variable to null:

      
        // This is a PHP file, so make sure it has the .php extension
        $pdo = null;
      
    

Conclusion

In this guide, we've explored how to connect to a different database using PHP. By understanding database drivers, installing necessary extensions, establishing connections, executing queries, and closing connections, you can effectively interact with various database management systems, expanding the capabilities of your PHP applications.

Remember to handle database connections securely, using best practices such as parameterized queries and proper error handling, to ensure the integrity and security of your data.

Quick Actions

Technologies

PHP
MySQLi
PDO
Database Connection

Featured Products

Discover amazing deals and products we recommend

Bonavita Coffee 8 in 1 ( Buy 5 boxes + 1 box FREE)

Bonavita Coffee 8 in 1 ( Buy 5 boxes + 1 box FREE)

Sustainably sourced, chemical-free beans for a delightful brew. Packed With Rich Nutrients. Coffee drink with mangosteen, guyabano and acai berry!

View Product
Ambi Pur Car Freshener Sky Breeze Value Pack Lavender Comfort Value Pack 2.2ml Car Vent Clip (Long-lasting Car Freshener, Air Freshener)

Ambi Pur Car Freshener Sky Breeze Value Pack Lavender Comfort Value Pack 2.2ml Car Vent Clip (Long-lasting Car Freshener, Air Freshener)

Ambi Pur Car Freshener Sky Breeze Value Pack Lavender Comfort Value Pack 2.2ml Car Vent Clip (Long-lasting Car Freshener, Air Freshener)

View Product
URU4500 Digital Persona Biometric Reader Fingerprint U.are.U 4500 Fingerprint Scanner With Free SDK

URU4500 Digital Persona Biometric Reader Fingerprint U.are.U 4500 Fingerprint Scanner With Free SDK

The U.are.U 4500 Fingerprint Reader is a USB peripheral perfect for individual desk top users, as well as multiple users in shared environments. Its compact design conserves desk space in enterprises, and its professional, modern appearance looks elegant in point-of-sale environments.

View Product
ANSEN Webcam for PC Laptop Online Class 2K 1080P HD USB Web Camera with Mic

ANSEN Webcam for PC Laptop Online Class 2K 1080P HD USB Web Camera with Mic

ANSEN 1080P Webcam for PC Laptop Online Class Webcams HD USB Web Camera with Mic Live Steam

View Product
TOPICAL HAIR GROWER TRINOXTERIDE20 (ROLL ON)

TOPICAL HAIR GROWER TRINOXTERIDE20 (ROLL ON)

After washing your hair, roll on your scalp or skin spot you want to grow hair and gently massage for 2-3 minutes, no need to wash out, oil-based easy to use, and visible results within 2-4 weeks (depending on the skin absorption)

View Product
NB North Bayou DUAL Monitor Arm Mount Stand F160 by NeatPH

NB North Bayou DUAL Monitor Arm Mount Stand F160 by NeatPH

The F160 dual screen desktop monitor arm has a durable Gas-strut design to enable adjustment of your screen to your desired height and angle. This allows you to experience your interface from the best possible viewing angle. This design is particularly useful in a professional environment for collaborative work that requires multiple screens, or any space where you need to efficiently fit multiple screens. A gravity spring pivot joint design offers effortless titling to eliminate awkward positioning.

View Product
Logitech Gaming Mouse G102 LIGHTSYNC 8,000 DPI Customizable RGB Lighting 6 Programmable Button Wired

Logitech Gaming Mouse G102 LIGHTSYNC 8,000 DPI Customizable RGB Lighting 6 Programmable Button Wired

Make the most of play time with G203—a gaming mouse in a variety of vibrant colors. With LIGHTSYNC technology, a gaming-grade sensor and a classic 6-button design, you’ll light up your game and your desk

View Product
Under Table Storage basket Cable Management Tray Desk Socket Holder Wire Organizer Rack Storage Rack

Under Table Storage basket Cable Management Tray Desk Socket Holder Wire Organizer Rack Storage Rack

【ADJUSTABLE CLAMP】Screw clamp is easy to remove and reattach, adjustable clamps securely onto desks up to 4cm/1.57inch thick and as narrow as 1.2cm/0.47inch for a near universal fit on most desks.

View Product
NESTEA Cleanse Lemon Cucumber Powdered Green Tea with Fiber 8.5g x 10

NESTEA Cleanse Lemon Cucumber Powdered Green Tea with Fiber 8.5g x 10

Refresh with a delicious blend of all-natural green tea, lemon and cucumber extracts with NEW NESTEA CLEANSE! It's high in fiber which aids in digestion, and has no added table sugar. So go ahead -- start your wellness journey with NESTEA CLEANSE! Ang Gaan with NESTEA!

View Product
Page 1 of 9