@oci_fetch_all返回正确长度的2d数组,但行为空

时间:2019-06-13 14:07:57

标签: php sql oracle

最近,我开始学习PHP和Oracle SQL。

我试图通过使用以下方法调用Department函数来从selectAllDepartments表中获取所有行的列表:

@oci_fetch_all($statement, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);

以上语句执行并返回具有正确长度的2D数组$res。但不幸的是我空了。

我试图通过以下方式在函数内echo $res进行迭代:

    for ($x = 0; $x < count($res); $x++) {
        for ($y = 0; $y < count($res[$x]); $y++) {
            echo $res[$x][$y];
            echo "<br>";
        }
    }

这是具有功能的类:

<?php

class DatabaseHelper
{

    const username = '***'; 
    const password = '***';
    const con_string = 'lab';

    // Since we need only one connection object, it can be stored in a member variable.
    // $conn is set in the constructor.
    protected $conn;

    // Create connection in the constructor
    public function __construct()
    {
        try {
            // Create connection
           $this->conn = @oci_connect(
                DatabaseHelper::username,
                DatabaseHelper::password,
                DatabaseHelper::con_string
            );

            //check if the connection object is != null
            if (!$this->conn) {
                die("DB error: Connection can't be established!");
            }

        } catch (Exception $e) {
            die("DB error: {$e->getMessage()}");
        }
    }

    public function __destruct()
    {
        // clean up
        @oci_close($this->conn);
    }

    public function selectAllDepartments($deptID, $deptName)
    {
        if ($deptID && ($deptID != '')) {
            $sql = "SELECT * FROM Department WHERE departmentID like '" . $deptID . "'";
        } elseif ($deptName && ($deptName != '')) {
            $sql = "SELECT * FROM Department WHERE departmentName like " . $deptName . "";
        } else {
            $sql = "SELECT * FROM Department";
        }

        $statement = @oci_parse($this->conn, $sql);

        @oci_execute($statement);
        @oci_fetch_all($statement, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);

        echo $sql;
        //clean up;
        @oci_free_statement($statement);

        for ($x = 0; $x < count($res); $x++) {
            for ($y = 0; $y < count($res[$x]); $y++) {
                echo $res[$x][$y];
                echo "<br>";
            }
        }

        return $res;
    }
}

我假设我要么错误地解析了数据,要么连接有问题。如果是这样,那么如何检查呢?

1 个答案:

答案 0 :(得分:0)

问题是我错误地调用了数组元素。应该通过以下方式完成:

foreach ($res as $dept) {
    echo $dept['DEPARTMENTID'];
    echo $dept['DEPARTMENTNAME'];
    echo $dept['NUMBEROFCAGES'];
}

或类似的for循环