PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
]
);
return $pdo;
} catch (PDOException $e) {
// Log error with more details
error_log("Database connection failed: " . $e->getMessage());
// Show detailed error for debugging (remove in production)
die("
Database Connection Failed
Error: " . htmlspecialchars($e->getMessage()) . "
Please check:
- Database credentials in config/database.php
- Database server is running
- Database name: " . DB_NAME . "
- Database user: " . DB_USER . "
- User has proper permissions
Update the DB_PASS in config/database.php with your actual database password.
");
}
}
// Initialize database connection
$pdo = initializeDatabase();
/**
* Execute a prepared statement with parameters
*/
function executeQuery($sql, $params = []) {
global $pdo;
if ($pdo === null) {
$pdo = initializeDatabase();
}
try {
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
return $stmt;
} catch (PDOException $e) {
error_log("Query execution failed: " . $e->getMessage() . " | SQL: " . $sql);
// Check if it's a "table doesn't exist" error during setup
if (strpos($e->getMessage(), "doesn't exist") !== false && basename($_SERVER['PHP_SELF']) === 'setup.php') {
// This is expected during setup - tables need to be created
return false;
}
throw new Exception("Database operation failed: " . $e->getMessage());
}
}
/**
* Get single row from database
*/
function fetchRow($sql, $params = []) {
$stmt = executeQuery($sql, $params);
return $stmt->fetch();
}
/**
* Get all rows from database
*/
function fetchAll($sql, $params = []) {
$stmt = executeQuery($sql, $params);
return $stmt->fetchAll();
}
/**
* Insert data and return last insert ID
*/
function insertData($table, $data) {
global $pdo;
$columns = array_keys($data);
$placeholders = array_map(function($col) { return ':' . $col; }, $columns);
$sql = "INSERT INTO {$table} (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $placeholders) . ")";
$stmt = executeQuery($sql, $data);
return $pdo->lastInsertId();
}
/**
* Update data in database
*/
function updateData($table, $data, $where, $whereParams = []) {
$setParts = array_map(function($col) { return $col . ' = :' . $col; }, array_keys($data));
$sql = "UPDATE {$table} SET " . implode(', ', $setParts) . " WHERE {$where}";
$params = array_merge($data, $whereParams);
return executeQuery($sql, $params);
}
?>