Current Location: Home> Latest Articles> How to Connect Oracle Database Using PHP PDO Extension and Execute Queries

How to Connect Oracle Database Using PHP PDO Extension and Execute Queries

M66 2025-06-18

How to Connect Oracle Database Using PHP PDO Extension and Execute Queries

PHP is a popular server-side programming language, while Oracle is a widely used relational database management system. This article demonstrates how to use PHP's PDO extension to connect to an Oracle database, execute SQL queries, and perform common database operations.

1. Install PDO_OCI Extension

To connect to an Oracle database using PHP, the first step is to install the PDO_OCI extension. Here's how you can do that:

  1. Ensure that the Oracle client is installed on your server.
  2. Edit the PHP configuration file (php.ini), and uncomment the following lines:
  3. extension=php_pdo.dll
    extension=php_pdo_oci.dll
  4. Save and close the php.ini file.
  5. Restart the web server.

2. Create a PDO Connection Object

After installing the PDO_OCI extension and restarting the server, you can create a PDO connection object to connect to the Oracle database using the following code:

<?php
$database_name = "//localhost/orcl"; // Database connection string
$username = "your_username"; // Replace with your username
$password = "your_password"; // Replace with your password

try {
    $conn = new PDO("oci:dbname=" . $database_name, $username, $password);
    echo "Database connection successful!";
} catch (PDOException $e) {
    echo "Database connection failed: " . $e->getMessage();
}
?>

3. Execute SQL Queries

Once connected to the Oracle database, you can execute SQL queries. Here's an example of a simple query:

<?php
$database_name = "//localhost/orcl"; // Database connection string
$username = "your_username"; // Replace with your username
$password = "your_password"; // Replace with your password

try {
    $conn = new PDO("oci:dbname=" . $database_name, $username, $password);
    echo "Database connection successful!<br>";
    
    $stmt = $conn->prepare("SELECT * FROM employees WHERE department_id = :department_id");
    $stmt->bindParam(':department_id', $department_id);
    $department_id = 100;
    $stmt->execute();

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "Employee ID: " . $row['employee_id'] . ", Name: " . $row['first_name'] . " " . $row['last_name'] . "<br>";
    }
} catch (PDOException $e) {
    echo "Database connection failed: " . $e->getMessage();
}
?>

In this example, we use PDO's prepare() method to prepare the SQL query, bind parameters using bindParam(), execute the query with execute(), and fetch the results with fetch().

Conclusion

This article has shown how to use the PHP PDO extension to connect to an Oracle database and execute queries. By following the steps outlined, you can easily integrate PHP with Oracle databases. We hope this guide has been helpful!