PHP is a widely used server-side programming language, and Oracle Database is a popular relational database management system. This article will guide you through the process of using PHP extension PDO (PHP Data Objects) to connect to an Oracle database.
To connect to an Oracle database, you first need to install the PDO_OCI extension. Below are the steps for installation:
extension=php_pdo.dll extension=php_pdo_oci.dll
Once the PDO_OCI extension is installed and the server is restarted, you can write PHP code to connect to the Oracle database. Here's an example:
<?php $database_name = "//localhost/orcl"; // Database connection string, localhost is the host, orcl is the database name $username = "your_username"; // Replace with your own username $password = "your_password"; // Replace with your own password try { $conn = new PDO("oci:dbname=" . $database_name, $username, $password); echo "Database connected successfully!"; } catch (PDOException $e) { echo "Failed to connect to database: " . $e->getMessage(); } ?>
Once the connection to the Oracle database is successful, you can execute SQL queries. Here’s a simple example of how to do so:
<?php $database_name = "//localhost/orcl"; // Database connection string $username = "your_username"; // Replace with your own username $password = "your_password"; // Replace with your own password try { $conn = new PDO("oci:dbname=" . $database_name, $username, $password); echo "Database connected successfully!<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 "Failed to connect to database: " . $e->getMessage(); } ?>
In the above example, we use PDO's prepare() method to prepare the SQL query and bind parameters with the bindParam() method. Then, we execute the query with execute() and fetch the results using the fetch() method.
This article explained how to use PHP extension PDO to connect to an Oracle database, with relevant example code. By following these steps, you will be able to interact with Oracle databases using PHP. I hope this article helps you in your learning journey!