How to connect to Oracle database through PHP
Introduction:
In web development, it is often necessary to interact with the database to store and retrieve data. Oracle Database is a widely used relational database management system, while PHP is a scripting language widely used for web development. This article will introduce how to use PHP to connect to the Oracle database and provide some code examples.
Steps:
Connect to the database
Use PHP's oci_connect function to Connect to Oracle database. Here is a simple example:
<?php // 定义数据库连接参数 $user = 'your_username'; $password = 'your_password'; $database = 'your_database'; // 连接到Oracle数据库 $connection = oci_connect($user, $password, $database); // 检查连接是否成功 if (!$connection) { $error = oci_error(); die("无法连接到Oracle数据库: " . $error['message']); } else { echo "成功连接到Oracle数据库"; } // 关闭数据库连接 oci_close($connection); ?>
Execute SQL Query
Once successfully connected to the Oracle database, we can execute SQL queries to retrieve data. Here is an example:
<?php // 定义数据库连接参数 $user = 'your_username'; $password = 'your_password'; $database = 'your_database'; // 连接到Oracle数据库 $connection = oci_connect($user, $password, $database); // 检查连接是否成功 if (!$connection) { $error = oci_error(); die("无法连接到Oracle数据库: " . $error['message']); } // 执行查询 $query = "SELECT * FROM your_table"; $statement = oci_parse($connection, $query); oci_execute($statement); // 获取查询结果 while ($row = oci_fetch_array($statement, OCI_ASSOC+OCI_RETURN_NULLS)) { echo $row['COLUMN1'] . ', ' . $row['COLUMN2'] . '<br>'; } // 关闭查询和数据库连接 oci_free_statement($statement); oci_close($connection); ?>
Insert and update data
In addition to querying data, we can also use PHP to insert and update data. The following is an example:
<?php // 定义数据库连接参数 $user = 'your_username'; $password = 'your_password'; $database = 'your_database'; // 连接到Oracle数据库 $connection = oci_connect($user, $password, $database); // 检查连接是否成功 if (!$connection) { $error = oci_error(); die("无法连接到Oracle数据库: " . $error['message']); } // 插入数据 $query = "INSERT INTO your_table (COLUMN1, COLUMN2) VALUES ('Value 1', 'Value 2')"; $statement = oci_parse($connection, $query); oci_execute($statement); // 更新数据 $query = "UPDATE your_table SET COLUMN1 = 'New Value' WHERE COLUMN2 = 'Value 2'"; $statement = oci_parse($connection, $query); oci_execute($statement); // 关闭查询和数据库连接 oci_free_statement($statement); oci_close($connection); ?>
Summary:
Through the introduction and sample code of this article, you should now know how to use PHP to connect to the Oracle database and perform queries, inserts, and updates Data manipulation. Remember to modify the connection parameters and SQL statements in the sample code according to your actual situation. I wish you good luck in connecting to Oracle database in PHP development!
The above is the detailed content of How to connect to Oracle database via PHP. For more information, please follow other related articles on the PHP Chinese website!