<?php
// Start session
session_start();
// Include database configuration
require_once '../../config/database.php';
// Check if user is logged in and has admin role
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
header("Location: ../../login.php");
exit();
}
// Check if the question_banks table exists
$table_check = $conn->query("SHOW TABLES LIKE 'question_banks'");
$table_exists = $table_check->num_rows > 0;
if (!$table_exists) {
// Create the question_banks table
$create_table_query = "
CREATE TABLE IF NOT EXISTS `question_banks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`description` text DEFAULT NULL,
`course_id` int(11) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`),
KEY `course_id` (`course_id`),
CONSTRAINT `question_banks_course_id_fk` FOREIGN KEY (`course_id`) REFERENCES `courses` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
";
if ($conn->query($create_table_query)) {
$success_message = "Question banks table created successfully.";
} else {
$error_message = "Error creating question banks table: " . $conn->error;
}
} else {
// Check if course_id field exists
$field_check = $conn->query("SHOW COLUMNS FROM `question_banks` LIKE 'course_id'");
$field_exists = $field_check->num_rows > 0;
if (!$field_exists) {
// Add course_id field
$add_field_query = "
ALTER TABLE `question_banks`
ADD COLUMN `course_id` int(11) DEFAULT NULL AFTER `description`,
ADD KEY `course_id` (`course_id`),
ADD CONSTRAINT `question_banks_course_id_fk` FOREIGN KEY (`course_id`) REFERENCES `courses` (`id`) ON DELETE SET NULL
";
if ($conn->query($add_field_query)) {
$success_message = "Course ID field added to question banks table successfully.";
} else {
$error_message = "Error adding course ID field: " . $conn->error;
}
} else {
$success_message = "Question banks table already exists with course_id field.";
}
}
// Redirect back to banks page
$_SESSION['success_message'] = $success_message ?? null;
$_SESSION['error_message'] = $error_message ?? null;
header("Location: ../banks.php");
exit();
?>