<?php
// Start session
session_start();
// Display all errors for diagnosis
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Database configuration
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'popularcomputer';
echo '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Database Repair Tool</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
body { padding: 20px; font-family: Arial, sans-serif; }
.status-box { margin-bottom: 20px; padding: 15px; border-radius: 5px; }
.error { background-color: #f8d7da; border-left: 5px solid #dc3545; }
.success { background-color: #d4edda; border-left: 5px solid #28a745; }
.info { background-color: #d1ecf1; border-left: 5px solid #17a2b8; }
.warning { background-color: #fff3cd; border-left: 5px solid #ffc107; }
.code { background: #f8f9fa; padding: 10px; border-radius: 5px; font-family: monospace; }
.navigation { margin-top: 30px; }
</style>
</head>
<body>
<div class="container">
<h1>Database Repair Tool</h1>
<p class="lead">This tool diagnoses and repairs database connectivity issues</p>';
// Check if we were redirected from a page with an error
if (isset($_SESSION['db_error'])) {
echo '<div class="status-box error">
<h4><i class="fas fa-exclamation-circle"></i> Page Error Detected</h4>
<p>' . htmlspecialchars($_SESSION['db_error']) . '</p>
<p>The following tests will help diagnose and fix the issue.</p>
</div>';
// Clear the error so it doesn't persist
unset($_SESSION['db_error']);
}
// Function to log messages
function log_message($message, $type = 'info') {
echo '<div class="status-box ' . $type . '">';
$icon = '';
switch($type) {
case 'success': $icon = '<i class="fas fa-check-circle"></i>'; break;
case 'error': $icon = '<i class="fas fa-exclamation-circle"></i>'; break;
case 'warning': $icon = '<i class="fas fa-exclamation-triangle"></i>'; break;
default: $icon = '<i class="fas fa-info-circle"></i>';
}
echo $icon . ' ' . $message;
echo '</div>';
}
// Test 1: Basic PHP & MySQL version check
echo '<h2>1. Environment Check</h2>';
log_message('PHP Version: ' . phpversion());
if (function_exists('mysqli_connect')) {
log_message('MySQLi extension is installed.', 'success');
} else {
log_message('MySQLi extension is NOT installed. This is required for database connectivity.', 'error');
}
if (class_exists('mysqli')) {
log_message('MySQLi class is available.', 'success');
// Check client info
try {
$mysqli_version = mysqli_get_client_info();
log_message('MySQL Client Info: ' . $mysqli_version, 'success');
} catch (Exception $e) {
log_message('Error getting MySQL client info: ' . $e->getMessage(), 'warning');
}
} else {
log_message('MySQLi class is NOT available. This is required for database connectivity.', 'error');
}
// Test 2: Basic Database Connectivity
echo '<h2>2. Database Connectivity</h2>';
try {
// Connect to server without database
$conn = new mysqli($db_host, $db_user, $db_pass);
if ($conn->connect_error) {
log_message('Failed to connect to MySQL server: ' . $conn->connect_error, 'error');
echo '<div class="status-box info">
<h4>Possible Solutions:</h4>
<ul>
<li>Check that MySQL server is running</li>
<li>Verify username and password</li>
<li>Check host configuration</li>
</ul>
</div>';
} else {
log_message('Successfully connected to MySQL server.', 'success');
// Check if the database exists
$db_result = $conn->query("SHOW DATABASES LIKE '$db_name'");
if ($db_result && $db_result->num_rows > 0) {
log_message("Database '$db_name' exists.", 'success');
// Try to select the database
if ($conn->select_db($db_name)) {
log_message("Successfully connected to database '$db_name'.", 'success');
// Check for required tables
$required_tables = ['users', 'categories', 'courses', 'testimonials'];
foreach ($required_tables as $table) {
$table_result = $conn->query("SHOW TABLES LIKE '$table'");
if ($table_result && $table_result->num_rows > 0) {
log_message("Table '$table' exists.", 'success');
// If testimonials table, check for rating column
if ($table == 'testimonials') {
$col_result = $conn->query("SHOW COLUMNS FROM testimonials LIKE 'rating'");
if ($col_result && $col_result->num_rows > 0) {
log_message("Column 'rating' exists in testimonials table.", 'success');
} else {
log_message("Adding 'rating' column to testimonials table...", 'info');
$add_col = $conn->query("ALTER TABLE testimonials ADD COLUMN rating INT NOT NULL DEFAULT 5");
if ($add_col) {
log_message("Successfully added 'rating' column.", 'success');
} else {
log_message("Failed to add 'rating' column: " . $conn->error, 'error');
}
}
}
// If users table, check for designation column
if ($table == 'users') {
$designation_col = $conn->query("SHOW COLUMNS FROM users LIKE 'designation'");
if ($designation_col && $designation_col->num_rows > 0) {
log_message("Column 'designation' exists in users table.", 'success');
} else {
log_message("Adding 'designation' column to users table...", 'info');
$add_col = $conn->query("ALTER TABLE users ADD COLUMN designation VARCHAR(255) DEFAULT NULL");
if ($add_col) {
log_message("Successfully added 'designation' column.", 'success');
} else {
log_message("Failed to add 'designation' column: " . $conn->error, 'error');
}
}
// Check for expertise column
$expertise_col = $conn->query("SHOW COLUMNS FROM users LIKE 'expertise'");
if ($expertise_col && $expertise_col->num_rows > 0) {
log_message("Column 'expertise' exists in users table.", 'success');
} else {
log_message("Adding 'expertise' column to users table...", 'info');
$add_col = $conn->query("ALTER TABLE users ADD COLUMN expertise TEXT DEFAULT NULL");
if ($add_col) {
log_message("Successfully added 'expertise' column.", 'success');
} else {
log_message("Failed to add 'expertise' column: " . $conn->error, 'error');
}
}
// Check for social_links column
$social_col = $conn->query("SHOW COLUMNS FROM users LIKE 'social_links'");
if ($social_col && $social_col->num_rows > 0) {
log_message("Column 'social_links' exists in users table.", 'success');
} else {
log_message("Adding 'social_links' column to users table...", 'info');
$add_col = $conn->query("ALTER TABLE users ADD COLUMN social_links TEXT DEFAULT NULL");
if ($add_col) {
log_message("Successfully added 'social_links' column.", 'success');
} else {
log_message("Failed to add 'social_links' column: " . $conn->error, 'error');
}
}
// Check for profile_image column
$image_col = $conn->query("SHOW COLUMNS FROM users LIKE 'profile_image'");
if ($image_col && $image_col->num_rows > 0) {
log_message("Column 'profile_image' exists in users table.", 'success');
} else {
log_message("Adding 'profile_image' column to users table...", 'info');
$add_col = $conn->query("ALTER TABLE users ADD COLUMN profile_image VARCHAR(255) DEFAULT NULL");
if ($add_col) {
log_message("Successfully added 'profile_image' column.", 'success');
} else {
log_message("Failed to add 'profile_image' column: " . $conn->error, 'error');
}
}
}
} else {
log_message("Table '$table' does not exist.", 'error');
}
}
} else {
log_message("Failed to select database '$db_name': " . $conn->error, 'error');
}
} else {
log_message("Database '$db_name' does not exist. Creating...", 'warning');
// Create the database
if ($conn->query("CREATE DATABASE IF NOT EXISTS $db_name")) {
log_message("Database '$db_name' created successfully.", 'success');
log_message("Please run this script again to check the database.", 'info');
} else {
log_message("Failed to create database: " . $conn->error, 'error');
}
}
}
} catch (Exception $e) {
log_message('Exception: ' . $e->getMessage(), 'error');
}
// Test 3: Check db_config.php script
echo '<h2>3. Database Configuration Script Check</h2>';
$config_file = __DIR__ . '/db_config.php';
if (file_exists($config_file)) {
log_message("db_config.php file exists.", 'success');
// Check the file contents
$config_contents = file_get_contents($config_file);
if (strpos($config_contents, 'new mysqli(') !== false) {
log_message("db_config.php contains mysqli connection code.", 'success');
} else {
log_message("db_config.php may not contain proper mysqli connection code.", 'warning');
}
// Check error handling
if (strpos($config_contents, 'catch') !== false) {
log_message("db_config.php contains error handling.", 'success');
} else {
log_message("db_config.php may not have proper error handling.", 'warning');
}
} else {
log_message("db_config.php file does not exist.", 'error');
}
// Test 4: Check instructor-details.php script
echo '<h2>4. Instructor Details Script Check</h2>';
$instructor_file = realpath(__DIR__ . '/../../instructor-details.php');
if (file_exists($instructor_file)) {
log_message("instructor-details.php file exists.", 'success');
// Check the file contents
$instructor_contents = file_get_contents($instructor_file);
// Look for validation code
if (strpos($instructor_contents, 'if (!$conn || $conn->connect_error)') !== false) {
log_message("instructor-details.php already contains connection validation code.", 'success');
} else {
log_message("instructor-details.php needs connection validation code.", 'warning');
log_message("We recommend adding this code after including db_config.php:", 'info');
echo '<div class="code">
if (!$conn || $conn->connect_error) {
die("Database connection failed: " . ($conn ? $conn->connect_error : "Connection object not initialized"));
}
</div>';
}
// Look for try-catch for checking designation column
if (strpos($instructor_contents, 'try {') !== false &&
strpos($instructor_contents, 'SHOW COLUMNS FROM users LIKE \'designation\'') !== false) {
log_message("instructor-details.php already contains try-catch for checking designation column.", 'success');
} else {
log_message("instructor-details.php needs try-catch for checking designation column.", 'warning');
log_message("We recommend wrapping the column check in a try-catch block:", 'info');
echo '<div class="code">
try {
$check_designation = $conn->query("SHOW COLUMNS FROM users LIKE \'designation\'");
if ($check_designation && $check_designation->num_rows > 0) {
$designation_exists = true;
}
} catch (Exception $e) {
// If there\'s an error checking for the column, we\'ll proceed without it
error_log("Error checking designation column: " . $e->getMessage());
}
</div>';
}
} else {
log_message("instructor-details.php file does not exist or is in a different location.", 'error');
log_message("Expected path: " . $instructor_file, 'info');
}
// Test 5: Check for common table issues
echo '<h2>5. Common Table Issues</h2>';
if (isset($conn) && !$conn->connect_error) {
// 1. Check for courses table column name mismatches
try {
$courses_columns = $conn->query("SHOW COLUMNS FROM courses");
if ($courses_columns) {
$found_columns = [];
while ($col = $courses_columns->fetch_assoc()) {
$found_columns[] = $col['Field'];
}
// Check if needed columns exist
$category_col = in_array('category', $found_columns) ? true : in_array('category_id', $found_columns);
$image_col = in_array('image', $found_columns) ? true : in_array('thumbnail', $found_columns);
$featured_col = in_array('is_featured', $found_columns) ? true : in_array('featured', $found_columns);
if (!$category_col) {
log_message("The 'category' or 'category_id' column is missing from the courses table.", 'error');
} else {
log_message("The category column exists in the courses table.", 'success');
// Check for column name mismatch
if (in_array('category_id', $found_columns) && !in_array('category', $found_columns)) {
log_message("Found 'category_id' column, but 'category' is needed based on current code. Fixing...", 'warning');
// First check if constraints exist
$constraints = $conn->query("
SELECT CONSTRAINT_NAME
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = '$db_name'
AND TABLE_NAME = 'courses'
AND COLUMN_NAME = 'category_id'
AND CONSTRAINT_NAME != 'PRIMARY'
");
if ($constraints && $constraints->num_rows > 0) {
while ($constraint = $constraints->fetch_assoc()) {
// Drop the constraint
$conn->query("ALTER TABLE courses DROP FOREIGN KEY " . $constraint['CONSTRAINT_NAME']);
log_message("Dropped foreign key constraint: " . $constraint['CONSTRAINT_NAME'], 'info');
}
}
// Now rename the column
if ($conn->query("ALTER TABLE courses CHANGE category_id category INT")) {
log_message("Successfully renamed 'category_id' to 'category'", 'success');
// Re-add the foreign key
$fk_query = "ALTER TABLE courses ADD CONSTRAINT courses_category_fk
FOREIGN KEY (category) REFERENCES categories(id) ON DELETE SET NULL";
if ($conn->query($fk_query)) {
log_message("Successfully re-added foreign key constraint", 'success');
} else {
log_message("Failed to add foreign key constraint: " . $conn->error, 'error');
}
} else {
log_message("Failed to rename column: " . $conn->error, 'error');
}
}
}
if (!$image_col) {
log_message("The 'image' or 'thumbnail' column is missing from the courses table.", 'error');
} else {
log_message("The image column exists in the courses table.", 'success');
// Check for column name mismatch
if (in_array('thumbnail', $found_columns) && !in_array('image', $found_columns)) {
log_message("Found 'thumbnail' column, but 'image' is needed based on current code. Fixing...", 'warning');
if ($conn->query("ALTER TABLE courses CHANGE thumbnail image VARCHAR(255)")) {
log_message("Successfully renamed 'thumbnail' to 'image'", 'success');
} else {
log_message("Failed to rename column: " . $conn->error, 'error');
}
}
}
if (!$featured_col) {
log_message("The 'is_featured' or 'featured' column is missing from the courses table.", 'error');
} else {
log_message("The featured column exists in the courses table.", 'success');
// Check for column name mismatch
if (in_array('featured', $found_columns) && !in_array('is_featured', $found_columns)) {
log_message("Found 'featured' column, but 'is_featured' is needed based on current code. Fixing...", 'warning');
if ($conn->query("ALTER TABLE courses CHANGE featured is_featured TINYINT(1) NOT NULL DEFAULT 0")) {
log_message("Successfully renamed 'featured' to 'is_featured'", 'success');
} else {
log_message("Failed to rename column: " . $conn->error, 'error');
}
}
}
} else {
log_message("Could not fetch columns from the courses table: " . $conn->error, 'error');
}
} catch (Exception $e) {
log_message("Error checking courses table: " . $e->getMessage(), 'error');
}
// 2. Check if enrollments table exists
try {
$check_enrollments = $conn->query("SHOW TABLES LIKE 'enrollments'");
if ($check_enrollments && $check_enrollments->num_rows == 0) {
log_message("The enrollments table does not exist. Creating...", 'warning');
$create_enrollments = $conn->query("
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
)
");
if ($create_enrollments) {
log_message("Successfully created enrollments table", 'success');
} else {
log_message("Failed to create enrollments table: " . $conn->error, 'error');
}
} else {
log_message("The enrollments table exists.", 'success');
}
} catch (Exception $e) {
log_message("Error checking enrollments table: " . $e->getMessage(), 'error');
}
} else {
log_message("Cannot check for common table issues - database connection is not available.", 'error');
}
// Navigation links
echo '<div class="navigation">
<h4>Next Steps:</h4>
<a href="../../instructor-details.php?id=1" class="btn btn-primary m-1">Test Instructor Details</a>
<a href="../testimonials.php" class="btn btn-info m-1">Test Testimonials</a>
<a href="fix_missing_columns.php" class="btn btn-warning m-1">Run Column Fix Script</a>
<a href="../../index.php" class="btn btn-success m-1">Return to Homepage</a>
<a href="../index.php" class="btn btn-secondary m-1">Go to Admin Dashboard</a>
<button class="btn btn-danger m-1" onclick="window.location.reload();">Run Tests Again</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>';
?>