2

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 Answers 2

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 ...".

Sign up to request clarification or add additional context in comments.

1 Comment

Does anyone know why it does that? Does fetchArray() call data on the DB directly instead of on the variable or what?
1

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
}

2 Comments

Thank you, but the problem is that the query returns many rows, that I want to loop over. Your solution allows to see only the first row.
Great! Haven't thought about that. That solves my problem. However, it is strange that I cannot return SQLite3Result object from function correctly...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.