【问题标题】:@oci_fetch_all returns 2d array of correct length, but rows are empty@oci_fetch_all 返回正确长度的二维数组,但行为空
【发布时间】:2019-10-28 03:48:45
【问题描述】:

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

我正在尝试通过调用selectAllDepartments 函数从Department 表中获取所有行的列表:

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

上述语句执行并返回具有正确长度的二维数组$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;
    }
}

我假设我错误地解析了数据,或者我的连接有问题。如果是,那怎么查?

【问题讨论】:

    标签: php sql oracle


    【解决方案1】:

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

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

    或者与普通的for循环类似

    【讨论】:

      猜你喜欢
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      • 2012-10-16
      • 1970-01-01
      相关资源
      最近更新 更多