从 PHP 连接到 Oracle 数据库


Connecting to Oracle database from PHP

我有一个Oracle数据库,我正在尝试连接到它。

出于某种原因,当我尝试以下代码时:

<?php
    include "header.php";
    // simply attempt to connect to the database
    /* If you are connecting to the Oracle database, the credentials are as follows: 
     * Username: ********
     * Password: ********
     * Hostname: **********
     * Port: 1521
     * Service name: ***********
    */
    $oracleConnect = true;
    if ($oracleConnect)
    {
        echo 'Attempting connection...<br>';
        $connection = null;
        try
        {
            $connection = oci_connect('user',
                'pass',
                'user@//hostname:1521/dbname');
        }
        catch (Exception $e)
        {
            echo $e->getMessage();
        }
        if (!$connection)
        {
            echo '<p>Something is wrong.</p>';
            $e = oci_error();
            trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
        }
        // if the connection has been established
        else
        {
            // tell the user and close it (this is a test)
            echo 'Connection established!!';
            oci_close($connection);
        }
    }
    else
    {
        $connection = new mysqli('host', 'user', 'password', 'database');
        echo ($connection) ? 'Database connection successful!' : 'Could not connect.';
    }
    include "footer.php";
?>

当我尝试上面的代码时,我得到"正在尝试连接..."打印,但没有别的。无论如何,它应该打印其他东西。可能出现什么问题?

我认为问题是连接字符串的user@部分。我认为这不是必需的,因为oci_connect有一个用户名参数。我可能是错的,我以前从未使用过 php 的 oracle,但关于 oci 连接的文档似乎也表明:

要使用轻松连接命名方法,PHP 必须与 Oracle 10g 或更高版本的客户端库链接。Oracle 10g 的轻松连接字符串格式为:[//]host_name[:p ort][/service_name]。从 Oracle 11g 开始,语法为:[//]host_name[:p ort][/service_name][:server_type][/instance_name]。通过在数据库服务器机器上运行 Oracle 实用程序 lsnrctl 状态,可以找到服务名称。

此外,据我所知,oci_connect不会抛出异常,因此您的尝试/捕获是无用的,除非您打算在它返回时抛出自己的false