59 lines
2.1 KiB
PHP
59 lines
2.1 KiB
PHP
<?php
|
|
require_once 'config.php';
|
|
|
|
try {
|
|
// 1. Connect without a database selected
|
|
$pdo_admin = new PDO('mysql:host='.DB_HOST.';charset=utf8mb4', DB_USER, DB_PASS, [
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
]);
|
|
|
|
// 2. Create the database if it doesn't exist
|
|
$pdo_admin->exec("CREATE DATABASE IF NOT EXISTS ".DB_NAME);
|
|
echo "Database '" . DB_NAME . "' created or already exists.\n";
|
|
|
|
// 3. Now, connect to the specific database and create the table
|
|
$pdo = db();
|
|
$sql = "
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
display_name VARCHAR(50) NOT NULL,
|
|
email VARCHAR(100) NOT NULL UNIQUE,
|
|
password_hash VARCHAR(255) NOT NULL,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);";
|
|
$pdo->exec($sql);
|
|
echo "Table 'users' created successfully (if it didn\'t exist).\n";
|
|
|
|
// 4. Run migrations
|
|
$migration_files = glob(__DIR__ . '/migrations/*.php');
|
|
foreach ($migration_files as $file) {
|
|
require_once $file;
|
|
echo "Ran migration: $file\n";
|
|
}
|
|
|
|
// 5. Seed the users table if it's empty
|
|
$stmt = $pdo->query("SELECT COUNT(*) FROM users");
|
|
if ($stmt->fetchColumn() == 0) {
|
|
$users = [
|
|
['display_name' => 'John Doe', 'email' => 'john.doe@example.com', 'password' => 'password123'],
|
|
['display_name' => 'Jane Smith', 'email' => 'jane.smith@example.com', 'password' => 'password123'],
|
|
['display_name' => 'Peter Jones', 'email' => 'peter.jones@example.com', 'password' => 'password123'],
|
|
];
|
|
|
|
$sql = "INSERT INTO users (display_name, email, password_hash) VALUES (:display_name, :email, :password_hash)";
|
|
$stmt = $pdo->prepare($sql);
|
|
|
|
foreach ($users as $user) {
|
|
$stmt->execute([
|
|
':display_name' => $user['display_name'],
|
|
':email' => $user['email'],
|
|
':password_hash' => password_hash($user['password'], PASSWORD_DEFAULT)
|
|
]);
|
|
}
|
|
echo "Seeded the users table with 3 sample users.\n";
|
|
}
|
|
|
|
|
|
} catch (PDOException $e) {
|
|
die("DB SETUP ERROR: " . $e->getMessage());
|
|
} |