最近我开始学习PHP和Oracle SQL。
我正在尝试通过使用以下命令调用selectAllDepartments
函数从Department
表中获取所有行的列表:
@oci_fetch_all($statement, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);
上面的语句执行并返回长度正确的二维数组$res
。但不幸的是对我来说是空的。
我试图通过以下方式遍历函数内的$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;
}
}
我认为要么是我错误地解析了数据,要么是我的连接出了问题。如果是,那么如何检查呢?
发布于 2019-06-14 03:13:53
问题是我错误地调用了数组元素。应该是通过以下方式完成的:
foreach ($res as $dept) {
echo $dept['DEPARTMENTID'];
echo $dept['DEPARTMENTNAME'];
echo $dept['NUMBEROFCAGES'];
}
或者类似于普通的for循环
https://stackoverflow.com/questions/56582376
复制相似问题