PHP code example of cooldogedev / libsql

1. Go to this page and download the library: Download cooldogedev/libsql library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cooldogedev / libsql example snippets


$pool = new ConnectionPool(PluginBase, [
    "provider" => "sqlite",
    "threads" => 2,
    "sqlite" => [
        "path" => "test.db"
    ]
]);

final class CustomerRetrievalQuery extends SQLiteQuery {
    public function onRun(SQLite3 $connection): void {
        $this->setResult($connection->query($this->getQuery())?->fetchArray() ?: []);
    }

    public function getQuery(): string { return "SELECT * FROM customers"; }
}

$query = new CustomerRetrievalQuery();
$query->execute(
    onSuccess: function (array $customers): void {
        foreach ($customers as $customer) {
            echo $customer["name"] . " " . $customer["lastName"] . ": " . $customer["age"];
            echo PHP_EOL;
        }
    },
    onFailure: function (SQLException $exception): void {
        echo "Failed to retrieve customers due to: " . $exception->getMessage();
    }
);

final class CustomerCreationQuery extends SQLiteQuery {
    public function __construct(
        protected string $name,
        protected string $lastName,
        protected int    $age
    ) {}

    public function onRun(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();

        $this->setResult($connection->changes() > 0);

        $statement->close();
    }

    public function getQuery(): string {
        return "INSERT OR IGNORE INTO customers (name, lastName, age) VALUES (:name, :lastName, :age)";
    }

    public function getName(): string { return $this->name; }
    public function getLastName(): string { return $this->lastName; }
    public function getAge(): int { return $this->age; }
}

$query = new CustomerCreationQuery("Saul", "Goodman", 41);
$pool->submit(
    query: $query,

    onSuccess: function (bool $created): void {
        echo $created ? "Customer created successfully!" : "Customer already exists!";
    },
    onFailure: function (SQLException $exception): void {
        echo "Failed to create the record due to: " . $exception->getMessage();
    }
);