在PHP中,SQLite3Result对象尚未正确初始化

时间:2014-03-06 16:35:13

标签: php sqlite

我的php文件中有那段代码(正常工作):

$db = new Database();
$stmt = $db->prepare("SELECT * FROM bills WHERE group_id=:gid");
$stmt->bindValue(":gid", $_SESSION['group_id'], SQLITE3_INTEGER);
if (($result = $stmt->execute()) === false) {
  echo "bad";
}

$bills = $result;
while ($bill = $bills->fetchArray()) {
  do stuff....
}

然后我尝试将所有与数据库相关的代码放在函数中:

function getBillsByGID($gid) {
    $db = new Database();
    $stmt = $db->prepare("SELECT * FROM bills WHERE group_id=:gid");
    $stmt->bindValue(":gid", $gid, SQLITE3_INTEGER);

    if (($result = $stmt->execute()) === false) {
        return null;
    }   

    return $result;
}

在原始文件中:

$bills = getBillsByGID($_SESSION['group_id']);
while ($bill = $bills->fetchArray()) {
       do stuff...
}

这会给我留言:"Warning: SQLite3Result::fetchArray(): The SQLite3Result object has not been correctly initialised in line 61"(与while($bill = $bills->fetchArray()一致))

调用该函数后,

var_dump($bills)会给出object(SQLite3Result)#10 (0) { }

那么我该如何制作一个能正常工作的功能?

2 个答案:

答案 0 :(得分:5)

您是否在关闭getBillsByGID中的语句?调用$ stmt-> close()会使您从$ stmt-> execute()获得的结果无效。之后,调用$ result-> fetchArray()将给出错误“SQLite3Result对象未在......中正确初始化”。

答案 1 :(得分:1)

我认为您需要在函数中获取数据,然后返回变量

function getBillsByGID($gid) {
    $db = new Database();
    $stmt = $db->prepare("SELECT * FROM bills WHERE group_id=:gid");
    $stmt->bindValue(":gid", $gid, SQLITE3_INTEGER);

    if ($stmt->execute() === false) {
        return null;
    }   

    $array = array();
    while($data = $stmt->fetchArray())
    {
         $array[] = $data;
    }

    return $array;
}

现在将函数分配给变量并循环抛出以获取数组的数据

$bills = getBillsByGID($_SESSION['group_id']);
foreach($bills as $data) {
     //do stuff with $data
}