PHP Oracle Database Connection: Step-by-Step

PHP can interact with an Oracle database by following these steps:

  1. To install the Oracle database driver: PHP requires a driver compatible with Oracle to connect and operate with the Oracle database. You can download and install the OCI8 driver, or use the PDO_OCI driver.
  2. Connect to an Oracle database: Use the oci_connect() function or the new PDO() method in PDO to establish a connection to an Oracle database.
  3. For example:
  4. // Connect using OCI8 driver
    $conn = oci_connect(‘username’, ‘password’, ‘localhost/XE’);

    // Connect using PDO_OCI driver
    $conn = new PDO(‘oci:dbname=localhost/XE’, ‘username’, ‘password’);

  5. Execute the query statement: Use the oci_parse() function from OCI8 or the query() method from PDO to execute SQL query statements.
  6. For example,
  7. // Execute a query using OCI8 driver
    $query = oci_parse($conn, ‘SELECT * FROM table_name’);
    oci_execute($query);

    // Execute a query using PDO_OCI driver
    $query = $conn->query(‘SELECT * FROM table_name’);

  8. Retrieve query results: Use the oci_fetch_array() function with OCI8 or the fetch() method with PDO to fetch query results.
  9. For example:
  10. // Retrieve query results using OCI8 driver
    while ($row = oci_fetch_array($query)) {
    // Process data of each row
    }

    // Retrieve query results using PDO_OCI driver
    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    // Process data of each row
    }

  11. Performing other database operations: PHP offers a range of OCI8 functions or PDO methods to execute various database operations, such as inserting, updating, deleting, as well as managing transactions and more.
  12. For example:
  13. Performing insert operation using OCI8 driver:
    $insert = oci_parse($conn, ‘INSERT INTO table_name (column1, column2) VALUES (:val1, :val2)’);
    oci_bind_by_name($insert, ‘:val1’, $value1);
    oci_bind_by_name($insert, ‘:val2’, $value2);
    oci_execute($insert);

    Executing insert operation using PDO_OCI driver:
    $insert = $conn->prepare(‘INSERT INTO table_name (column1, column2) VALUES (?, ?)’);
    $insert->execute([$value1, $value2]);

This is just a simple example, for more detailed instructions refer to the official PHP documentation or other resources.

bannerAds