35067-vm/db/setup.php
Flatlogic Bot b200618254 eco-grow
2025-10-20 06:45:18 +00:00

61 lines
2.1 KiB
PHP

<?php
require_once 'config.php';
try {
// 1. Connect to MySQL server (without selecting a database)
$pdo_server = new PDO('mysql:host='.DB_HOST, DB_USER, DB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
// 2. Create the database if it doesn't exist
$pdo_server->exec("CREATE DATABASE IF NOT EXISTS `".DB_NAME."`");
echo "Database '".DB_NAME."' created or already exists.<br>";
// 3. Connect to the specific database
$pdo_db = db(); // Use the original helper function which connects to the DB
// 4. Create the users table
$sql = "
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
role ENUM('admin', 'vendor', 'customer') NOT NULL DEFAULT 'customer',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB;
";
$pdo_db->exec($sql);
echo "Table 'users' created successfully (if it didn't exist).<br>";
// Add 'customer' role to existing tables
try {
$pdo_db->exec("ALTER TABLE users MODIFY COLUMN role ENUM('admin', 'vendor', 'customer') NOT NULL DEFAULT 'customer'");
echo "Column 'role' in 'users' table updated successfully to include 'customer'.<br>";
} catch (PDOException $e) {
// This might fail if the column is already correct, which is fine.
echo "Could not alter 'users' table, probably already up-to-date.<br>";
}
// 5. Create the products table
$sql_products = "
CREATE TABLE IF NOT EXISTS products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
vendor_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (vendor_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=INNODB;
";
$pdo_db->exec($sql_products);
echo "Table 'products' created successfully (if it didn't exist).<br>";
echo "<hr>Setup complete!";
} catch (PDOException $e) {
die("DB SETUP ERROR: ". $e->getMessage());
}