Skip to content

Examples

Doge edited this page Sep 1, 2021 · 2 revisions

Retrieve all customer records

$connector = new DatabaseConnector($this,
    [
        "provider" => "sqlite",
        "sqlite" => [
            "data-file" => "test.db"
        ]
    ]
);

$query = new class extends SQLiteQuery {

    public function handleIncomingConnection(SQLite3 $connection): ?array
    {
        return $connection->query($this->getQuery())?->fetchArray() ?: null;
    }

    public function getQuery(): string
    {
        return "SELECT * FROM " . $this->getTable();
    }
};

$connector->submitQuery($query, "customers",
    function (?array $customers): void {
        if (!$customers) {
            echo "No customers found";
            return;
        }
        foreach ($customers as $customer) {
            echo $customer["name"];
        }
    },
    function (PromiseError $error): void {
        echo "An error occurred with the message " . $error->getMessage();
    }
);

Create a new customer record

$connector = new DatabaseConnector($this,
    [
        "provider" => "sqlite",
        "sqlite" => [
            "data-file" => "test.db"
        ]
    ]
);

$query = new class extends SQLiteQuery {
    public function __construct(
        protected string $name = "John",
        protected string $lastName = "Smith",
        protected int    $age = 40
    ) {}

    public function getName(): string { return $this->name; }

    public function getLastName(): string { return $this->lastName; }

    public function getAge(): int { return $this->age; }

    public function handleIncomingConnection(SQLite3 $connection): bool
    {
        $statement = $connection->prepare($this->getQuery());
        $statement->bindValue(":name", $this->getName());
        $statement->bindValue(":lastName", $this->getLastName());
        $statement->bindValue(":age", $this->getAge());
        $statement->execute();
        $statement->close();
        return true;
    }

    public function getQuery(): string
    {
        return "INSERT OR IGNORE INTO " . $this->getTable() . " (name, lastName, age) VALUES (:name, :lastName, :age)";
    }
};

$connector->submitQuery($query, "customers",
    function (): void {
        echo "Successfully created a new record!";
    },
    function (PromiseError $error): void {
        echo "An error occurred with the message " . $error->getMessage();
    }
);

Projects using libSQL

Clone this wiki locally