49 lines
1.5 KiB
PHP
49 lines
1.5 KiB
PHP
<?php
|
|
class Database {
|
|
function __construct($path = null) {
|
|
if (is_null($path)) {
|
|
$path = "sqlite:" . __DIR__ . "/../../users.sqlite";
|
|
}
|
|
$this->path = $path;
|
|
}
|
|
|
|
function connect($username = null, $password=null) {
|
|
if (!is_null($username) && !is_null($password)) {
|
|
$this->dbh = new PDO($this->path, $username, $password);
|
|
} else {
|
|
$this->dbh = new PDO($this->path) or die("cannot open the database");
|
|
}
|
|
return $this->dbh;
|
|
}
|
|
|
|
function create_tables() {
|
|
// Create users table.
|
|
$users_table_query = "CREATE TABLE IF NOT EXISTS users (
|
|
username VARCHAR(10) NOT NULL PRIMARY KEY,
|
|
name VARCHAR(255) NOT NULL,
|
|
password VARCHAR(255) NOT NULL,
|
|
active INTEGER NOT NULL DEFAULT 1
|
|
)";
|
|
$this->dbh->exec($users_table_query);
|
|
|
|
if ($this->isError() !== false) {
|
|
throw new Exception("Couldn\"t create table: {$this->error}");
|
|
}
|
|
}
|
|
|
|
function isError() {
|
|
if (is_null($this->dbh->errorInfo()[1])) {
|
|
return false;
|
|
}
|
|
$this->error = $this->dbh->errorInfo()[2];
|
|
return true;
|
|
}
|
|
|
|
function getTotalCount($table_name, $suffix = "") {
|
|
$sql = "SELECT COUNT(*) FROM $table_name $suffix";
|
|
$result = $this->dbh->prepare($sql);
|
|
$result->execute();
|
|
return $result->fetchColumn();
|
|
}
|
|
}
|