jet's avatar
Level 1

Uncaught Error: The SQLite3 object has not been correctly initialised or is already closed

I'm using SQLite to create an API with PHP 8 but I have this error Uncaught Error: The SQLite3 object has not been correctly initialised or is already closed here is the db.php

<?php

class SQLiteDB extends SQLite3
{
  function __construct()
  {
     // $this->open('../db/development_db.sqlite3');
  }

}
$db = new SQLiteDB('sqlite:../db/development_db.sqlite3');
if(!$db){
  echo $db->lastErrorMsg();
} else {
  echo "Yes, Opened database successfully<br/>\n";
}

network

<?php
class Network{

    // database dbection and table name
    private $db;
    private $db_table = "network";
    // object properties
    public $id;
    public $name;
    public $uuid;
    public $created;

    // constructor with $db as database dbection
    public function __construct($db){
        $this->db = $db;
    }

public function read()
{
    $query = "SELECT id, name,uuid, created FROM " . $this->db_table . "";

    try {
        $query = $this->db->query($query);
        $result = $query->fetchAll(\PDO::FETCH_ASSOC);
        return $result;

    } catch (\PDOException $e) {
        exit($e->getMessage());
    }
}

read.php

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// database connection will be here

// include database and object files
include_once '../config/db.php';
include_once '../objects/network.php';

//instantiate database and network object
$database = new SQLiteDB();
// $db = $database->getConnection();

// initialize object
$network = new Network($database);

// read networks will be here

// query networks
$stmt = $network->read();
$num = $stmt->rowCount();

// check if more than 0 record found
if($num>0){

    // networks array
    $networks_arr=array();
    $networks_arr["records"]=array();

    // retrieve our table contents
    // fetch() is faster than fetchAll()
    // http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        // extract row
        // this will make $row['name'] to
        // just $name only
        extract($row);

        $network_item=array(
            "id" => $id,
            "name" => $name,
            "created" => $created,
            "uuid" => html_entity_decode($uuid),

        );

        array_push($networks_arr["records"], $network_item);
    }

    // set response code - 200 OK
    http_response_code(200);

    // show networks data in json format
    echo json_encode($networks_arr);
}

// no networks found will be here

else{

    // set response code - 404 Not found
    http_response_code(404);

    // tell the user no networks found
    echo json_encode(
        array("message" => "No networks found.")
    );
}
0 likes
0 replies

Please or to participate in this conversation.