Current Location: Home> Latest Articles> Complete Guide to Connecting and Querying Oracle Database with PHP

Complete Guide to Connecting and Querying Oracle Database with PHP

M66 2025-06-23

How to Connect to Oracle Database with PHP

Before operating Oracle databases with PHP, make sure that the Oracle client software is installed locally and the OCI8 extension is enabled in PHP to communicate with the Oracle database. Once the environment is ready, you can establish a database connection through PHP code.

// Use oci_connect function to connect to Oracle database
$connect = oci_connect($username, $password, "$host:$port/$sid");

// Check if connection is successful
if (!$connect) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
} else {
    echo "Successfully connected to Oracle database!";
}

?>

Querying Oracle Database Data Using PHP

After successful connection, you can execute SQL queries via PHP to retrieve the data needed from the Oracle database. The code uses oci_parse() to prepare the SQL, oci_execute() to run the query, and oci_fetch_array() to fetch results. Sample code is as follows:

// SQL query statement
$sql = "SELECT * FROM table_name";

// Prepare SQL query statement
$statement = oci_parse($connect, $sql);

// Execute SQL query
$result = oci_execute($statement);

// Check if query executed successfully
if (!$result) {
    $e = oci_error($statement);
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
} else {
    // Loop through and print query results
    while ($row = oci_fetch_array($statement, OCI_ASSOC + OCI_RETURN_NULLS)) {
        foreach ($row as $item) {
            echo $item . " ";
        }
        echo "<br>";
    }
}

?>

In the code above, `SELECT * FROM table_name` is a sample query; please replace it with your actual table name and query conditions. The parameters `OCI_ASSOC + OCI_RETURN_NULLS` ensure the fetch returns an associative array including null values.

Closing the Oracle Database Connection

After completing the query, it’s recommended to close the database connection to free system resources. Use the oci_close() function as shown below:

// Close Oracle database connection
oci_close($connect);

echo "Oracle database connection closed successfully!";

?>

Summary

The key steps to operate Oracle databases with PHP include environment setup, connecting to the database, executing queries, and closing the connection. Use oci_connect() to establish a connection, oci_parse() and oci_execute() to execute SQL statements, oci_fetch_array() to get query results, and finally oci_close() to close the connection. Mastering these basic operations allows developers to easily interact with Oracle databases via PHP and fulfill various business needs.

This article has provided a comprehensive explanation of querying Oracle databases using PHP and is intended to assist you in your development practice.