Path : /home/vishqocm/pcib.in/admin/database/
File Upload :
Current File : /home/vishqocm//pcib.in/admin/database/db_config.php

<?php
// Include admin functions
require_once __DIR__ . '/admin_functions.php';

// Database configuration
$db_host = 'localhost';
$db_user = 'vishqocm_popularcomputer23';
$db_pass = 'popularcomputer23';
$db_name = 'vishqocm_popularcomputer23';

// Create database connection
try {
    // First connect without selecting a database
    $conn = new mysqli($db_host, $db_user, $db_pass);
    
    // Check connection
    if ($conn->connect_error) {
        throw new Exception("Connection failed: " . $conn->connect_error);
    }
    
    // Create database if it doesn't exist
    $sql = "CREATE DATABASE IF NOT EXISTS " . $db_name;
    if (!$conn->query($sql)) {
        throw new Exception("Error creating database: " . $conn->error);
    }
    
    // Select the database
    $conn->select_db($db_name);
    
    // Set charset to utf8mb4
    $conn->set_charset("utf8mb4");
    
    // Create necessary tables if they don't exist
    $tables = [
        // Users table
        "CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            username VARCHAR(50) NOT NULL UNIQUE,
            password VARCHAR(255) NOT NULL,
            email VARCHAR(100) NOT NULL UNIQUE,
            first_name VARCHAR(50) NOT NULL,
            last_name VARCHAR(50) NOT NULL,
            phone VARCHAR(20) DEFAULT NULL,
            bio TEXT DEFAULT NULL,
            profile_image VARCHAR(255) DEFAULT NULL,
            designation VARCHAR(255) DEFAULT NULL,
            expertise TEXT DEFAULT NULL,
            social_links TEXT DEFAULT NULL,
            role ENUM('admin', 'instructor', 'student') NOT NULL DEFAULT 'student',
            status ENUM('active', 'inactive', 'pending') NOT NULL DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )",
        
        // Categories table
        "CREATE TABLE IF NOT EXISTS categories (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            description TEXT,
            status ENUM('active', 'inactive') NOT NULL DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )",
        
        // Courses table
        "CREATE TABLE IF NOT EXISTS courses (
            id INT AUTO_INCREMENT PRIMARY KEY,
            title VARCHAR(255) NOT NULL,
            description TEXT,
            category INT,
            instructor_id INT,
            price DECIMAL(10,2) NOT NULL DEFAULT 0.00,
            discount_price DECIMAL(10,2),
            duration VARCHAR(50),
            level ENUM('beginner', 'intermediate', 'advanced') NOT NULL DEFAULT 'beginner',
            image VARCHAR(255),
            is_featured TINYINT(1) NOT NULL DEFAULT 0,
            status ENUM('active', 'inactive', 'draft') NOT NULL DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (category) REFERENCES categories(id) ON DELETE SET NULL,
            FOREIGN KEY (instructor_id) REFERENCES users(id) ON DELETE SET NULL
        )",
        
        // Enrollments table
        "CREATE TABLE IF NOT EXISTS enrollments (
            id INT AUTO_INCREMENT PRIMARY KEY,
            course_id INT NOT NULL,
            user_id INT NOT NULL,
            enrollment_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            status ENUM('active', 'completed', 'cancelled') DEFAULT 'active',
            FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )",
        
        // Course reviews table
        "CREATE TABLE IF NOT EXISTS course_reviews (
            id INT AUTO_INCREMENT PRIMARY KEY,
            course_id INT NOT NULL,
            user_id INT NOT NULL,
            rating DECIMAL(2,1) NOT NULL,
            review TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )",
        
        // Testimonials table
        "CREATE TABLE IF NOT EXISTS testimonials (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            content TEXT NOT NULL,
            course_name VARCHAR(255),
            rating INT NOT NULL DEFAULT 5,
            status ENUM('pending', 'approved', 'rejected') NOT NULL DEFAULT 'pending',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )",
        
        // Institute stats table
        "CREATE TABLE IF NOT EXISTS institute_stats (
            id INT AUTO_INCREMENT PRIMARY KEY,
            total_students INT NOT NULL DEFAULT 0,
            total_courses INT NOT NULL DEFAULT 0,
            total_teachers INT NOT NULL DEFAULT 0,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )",
        
        // Site settings table
        "CREATE TABLE IF NOT EXISTS site_settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            setting_key VARCHAR(100) NOT NULL UNIQUE,
            setting_value TEXT,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )"
    ];
    
    // Create tables
    foreach ($tables as $table_query) {
        if (!$conn->query($table_query)) {
            error_log("Error creating table: " . $conn->error);
        }
    }
    
    // Insert default data if tables are empty
    
    // Check if site_settings is empty
    $result = $conn->query("SELECT COUNT(*) as count FROM site_settings");
    if ($result && $result->fetch_assoc()['count'] == 0) {
        // Insert default site settings
        $default_settings = [
            "INSERT INTO site_settings (setting_key, setting_value) VALUES ('site_name', 'Popular Computer Institute')",
            "INSERT INTO site_settings (setting_key, setting_value) VALUES ('site_tagline', 'Computer Education Institute')",
            "INSERT INTO site_settings (setting_key, setting_value) VALUES ('primary_color', '#4e73df')",
            "INSERT INTO site_settings (setting_key, setting_value) VALUES ('contact_email', '[email protected]')",
            "INSERT INTO site_settings (setting_key, setting_value) VALUES ('contact_phone', '+91 1234567890')"
        ];
        
        foreach ($default_settings as $setting_query) {
            $conn->query($setting_query);
        }
    }
    
    // Check if institute_stats is empty
    $result = $conn->query("SELECT COUNT(*) as count FROM institute_stats");
    if ($result && $result->fetch_assoc()['count'] == 0) {
        // Insert default stats
        $conn->query("INSERT INTO institute_stats (total_students, total_courses, total_teachers) VALUES (100, 10, 5)");
    }
    
    // Create a function to safely run queries
    if (!function_exists('safe_query')) {
        function safe_query($connection, $query) {
            if ($connection instanceof mysqli && !$connection->connect_error) {
                return $connection->query($query);
            }
            return false;
        }
    }
} catch (Exception $e) {
    // Log error but don't display it on the homepage
    error_log("Database connection failed: " . $e->getMessage());
    
    // Create a minimal mysqli connection that won't throw errors
    $conn = new mysqli();
    
    // Display repair link for admin pages
    $script_name = $_SERVER['SCRIPT_NAME'] ?? '';
    if (strpos($script_name, '/admin/') !== false) {
        // Only show this notice once per request
        echo '<div style="margin: 20px; padding: 15px; background-color: #f8d7da; border-left: 5px solid #dc3545; border-radius: 5px;">';
        echo '<h4 style="color: #721c24; margin-top: 0;">Database Connection Error</h4>';
        echo '<p>' . htmlspecialchars($e->getMessage()) . '</p>';
        echo '<p><a href="/admin/database/db_repair.php" style="color: #721c24; text-decoration: underline; font-weight: bold;">Run the Database Repair Tool</a></p>';
        echo '</div>';
    }
}

// Function to check if database connection is valid
function is_database_connected() {
    global $conn;
    return ($conn instanceof mysqli && !$conn->connect_error);
}