On Windows, you can enable the drivers by editing the php.ini file and uncommenting the following lines:
;extension=php_pdo_oci.dll ;extension=php_oci8.dll
Then restart your Apache or Nginx server to apply the changes.
On Linux, installation is typically done via PECL commands or manual compilation of OCI8 or PDO_OCI extensions. The specific steps vary depending on your operating system and PHP version. Refer to the official PHP documentation for guidance.
$dsn = 'oci:dbname=//hostname:port/oracle_sid';
$username = 'your_username';
$password = 'your_password';
try {
$conn = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
Here, $dsn contains the Oracle host, port, and SID information. $username and $password are the credentials needed to connect.
$sql = 'SELECT * FROM employees';
$stmt = $conn->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo $row['employee_id'] . ' ' . $row['first_name'] . ' ' . $row['last_name'] . '<br>';
}
In this code, $stmt represents the result set. fetchAll retrieves all rows as an associative array, which are then output one by one in a loop.
$sql = 'SELECT * FROM employees WHERE department_id = :dept_id';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':dept_id', $dept_id);
$dept_id = 1;
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo $row['employee_id'] . ' ' . $row['first_name'] . ' ' . $row['last_name'] . '<br>';
}
The placeholder ":dept_id" is used for the condition. bindParam binds the actual variable, and then execute runs the query.
Related Tags:
PDO