doure5236
doure5236
采纳率0%
2014-03-06 16:35

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

已采纳

I have that piece of code in my php file (correctly working):

$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....
}

Then I try to put all database related code in function:

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;
}

And in the original file:

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

That gives me message: "Warning: SQLite3Result::fetchArray(): The SQLite3Result object has not been correctly initialised in line 61" (line with while($bill = $bills->fetchArray()))

var_dump($bills) after calling the function gives object(SQLite3Result)#10 (0) { }

So how do I make a function which will work properly?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongzhuo5425 dongzhuo5425 7年前

    I think you need to fetch data in your function and then return your variable

    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;
    }
    

    Now assign the function to a variable and loop throw to get your array's data

    $bills = getBillsByGID($_SESSION['group_id']);
    foreach($bills as $data) {
         //do stuff with $data
    }
    
    点赞 评论 复制链接分享
  • dongpei3245 dongpei3245 7年前

    Are you closing the statement in your getBillsByGID? Calling $stmt->close() invalidates the result you got from $stmt->execute(). After that, calling $result->fetchArray() will give the error "The SQLite3Result object has not been correctly initialised in ...".

    点赞 评论 复制链接分享

相关推荐