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.
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:
extension=php_pdo.dll
extension=php_pdo_oci.dll
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(); } ?>
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().
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!