34646-vm/db/config.php
2025-10-04 10:27:48 +00:00

41 lines
1.4 KiB
PHP

<?php
function db() {
static $pdoconn = null;
if ($pdoconn === null) {
$host = '127.0.0.1';
$db = 'shortkenny';
$user = 'user';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
// Create database if it doesn't exist
$dbh = new PDO("mysql:host=$host", $user, $pass);
$dbh->exec("CREATE DATABASE IF NOT EXISTS `$db`;")
or die(print_r($dbh->errorInfo(), true));
$pdoconn = new PDO($dsn, $user, $pass, $options);
// Create table
$pdoconn->exec("
CREATE TABLE IF NOT EXISTS links (
id INT AUTO_INCREMENT PRIMARY KEY,
original_url VARCHAR(2048) NOT NULL,
short_code VARCHAR(10) NOT NULL UNIQUE,
click_count INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
");
} catch ("PDOException" $e) {
throw new "::PDOException($e->getMessage(), (int)$e->getCode());
}
}
return $pdoconn;
}