Project_Bank / project_add.php
Kshitij2604's picture
Upload 30 files
102fe5c verified
<?php
// Include database connection and authentication
require_once 'includes/db_connect.php';
require_once 'includes/domain_utils.php';
require_once 'includes/auth_check.php';
// Ensure only faculty can access this page
requireFaculty();
// Get all domain tables
$domainTables = getDomainTables($conn);
$domainDescriptions = getDomainDescriptions($conn);
$success = '';
$error = '';
// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Validate form data
$domainNumber = isset($_POST['domain']) ? intval($_POST['domain']) : 0;
$projectName = isset($_POST['project_name']) ? trim($_POST['project_name']) : '';
$projectType = isset($_POST['project_type']) ? trim($_POST['project_type']) : '';
$description = isset($_POST['description']) ? trim($_POST['description']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$links = isset($_POST['links']) ? trim($_POST['links']) : '';
// Additional fields (if any)
$additionalFields = [];
foreach ($_POST as $key => $value) {
if (strpos($key, 'additional_') === 0) {
$fieldName = substr($key, 11); // Remove 'additional_' prefix
$additionalFields[$fieldName] = trim($value);
}
}
// Basic validation
if ($domainNumber <= 0 || empty($projectName) || empty($projectType)) {
$error = "Please provide domain, project name, and project type.";
} else {
// Determine domain table name
$domainTable = "domain_" . $domainNumber;
// Check if the domain table exists
$tableCheckQuery = "SHOW TABLES LIKE '$domainTable'";
$tableExists = $conn->query($tableCheckQuery)->num_rows > 0;
if (!$tableExists) {
$error = "Selected domain table does not exist.";
} else {
// Get the correct project name field for this domain
$projectNameField = getProjectNameField($conn, $domainTable);
// Get the columns of the domain table to determine field structure
$columnsQuery = "SHOW COLUMNS FROM $domainTable";
$columnsResult = $conn->query($columnsQuery);
$columns = [];
while ($column = $columnsResult->fetch_assoc()) {
$columns[$column['Field']] = $column;
}
// Generate a new project ID
$maxIdQuery = "SELECT MAX(Project_ID) as max_id FROM $domainTable";
$maxIdResult = $conn->query($maxIdQuery);
$maxId = 1; // Default if no projects exist
if ($maxIdResult && $row = $maxIdResult->fetch_assoc()) {
$maxId = (!is_null($row['max_id'])) ? intval($row['max_id']) + 1 : 1;
}
// Prepare the SQL for insertion
$fields = ['Project_ID'];
$values = [$maxId];
$types = 'i'; // integer for Project_ID
// Add Domain_ID field if it exists
if (isset($columns['Domain_ID'])) {
$fields[] = 'Domain_ID';
$domainId = "D-" . $domainNumber;
$values[] = $domainId;
$types .= 's'; // string for Domain_ID
}
// Add project name field
$fields[] = $projectNameField;
$values[] = $projectName;
$types .= 's'; // string for Project Name
// Add project type field (H/S)
if (isset($columns['H/S'])) {
$fields[] = 'H/S';
$values[] = $projectType;
$types .= 's'; // string for H/S
}
// Add description field
if (isset($columns['Description']) && !empty($description)) {
$fields[] = 'Description';
$values[] = $description;
$types .= 's'; // string for Description
}
// Add email field
if (isset($columns['Email']) && !empty($email)) {
$fields[] = 'Email';
$values[] = $email;
$types .= 's'; // string for Email
}
// Add links field
if (isset($columns['Links']) && !empty($links)) {
$fields[] = 'Links';
$values[] = $links;
$types .= 's'; // string for Links
}
// Add additional fields
foreach ($additionalFields as $field => $value) {
if (isset($columns[$field]) && !empty($value)) {
$fields[] = $field;
$values[] = $value;
$types .= 's'; // string for additional fields
}
}
// Prepare and execute the insert query
$fieldStr = implode(', ', array_map(function($field) { return "`$field`"; }, $fields));
$placeholders = implode(', ', array_fill(0, count($fields), '?'));
$insertQuery = "INSERT INTO $domainTable ($fieldStr) VALUES ($placeholders)";
$stmt = $conn->prepare($insertQuery);
if ($stmt) {
// Dynamically bind parameters
$params = array_merge([$types], $values);
$ref_params = [];
foreach ($params as $key => $value) {
$ref_params[$key] = &$params[$key];
}
call_user_func_array([$stmt, 'bind_param'], $ref_params);
if ($stmt->execute()) {
$success = "Project added successfully with ID: $maxId";
// Clear form after successful submission
$projectName = $description = $email = $links = '';
$projectType = '';
$additionalFields = [];
} else {
$error = "Error adding project: " . $stmt->error;
}
$stmt->close();
} else {
$error = "Error preparing query: " . $conn->error;
}
}
}
}
// Include header
include 'includes/header.php';
?>
<div class="row mb-4">
<div class="col-md-12">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="index.php">Home</a></li>
<li class="breadcrumb-item"><a href="domains.php">Domains</a></li>
<li class="breadcrumb-item"><a href="project_manage.php">Manage Projects</a></li>
<li class="breadcrumb-item active">Add Project</li>
</ol>
</nav>
<div class="d-flex justify-content-between align-items-center">
<h2><i class="fas fa-plus-circle me-2"></i> Add New Project</h2>
<a href="project_manage.php" class="btn btn-secondary">
<i class="fas fa-arrow-left me-1"></i> Back to Projects
</a>
</div>
</div>
</div>
<?php if (!empty($success)): ?>
<div class="alert alert-success">
<i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
</div>
<?php endif; ?>
<?php if (!empty($error)): ?>
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
</div>
<?php endif; ?>
<div class="row">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header bg-primary text-white">
<h5 class="mb-0"><i class="fas fa-edit me-2"></i> Project Details</h5>
</div>
<div class="card-body">
<form method="post" action="project_add.php" id="projectForm">
<div class="row">
<div class="col-md-6 mb-3">
<label for="domain" class="form-label">Domain *</label>
<select class="form-select" id="domain" name="domain" required>
<option value="">Select Domain</option>
<?php foreach ($domainTables as $domainTable):
$domainNum = str_replace('domain_', '', $domainTable);
$domainDesc = isset($domainDescriptions[$domainNum]) ? $domainDescriptions[$domainNum] : "Domain $domainNum";
?>
<option value="<?php echo $domainNum; ?>" <?php echo (isset($_POST['domain']) && $_POST['domain'] == $domainNum) ? 'selected' : ''; ?>>
Domain <?php echo $domainNum; ?>: <?php echo htmlspecialchars($domainDesc); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-6 mb-3">
<label for="project_type" class="form-label">Project Type *</label>
<select class="form-select" id="project_type" name="project_type" required>
<option value="">Select Type</option>
<option value="Hardware" <?php echo (isset($_POST['project_type']) && $_POST['project_type'] == 'Hardware') ? 'selected' : ''; ?>>Hardware</option>
<option value="Software" <?php echo (isset($_POST['project_type']) && $_POST['project_type'] == 'Software') ? 'selected' : ''; ?>>Software</option>
</select>
</div>
</div>
<div class="mb-3">
<label for="project_name" class="form-label">Project Name *</label>
<input type="text" class="form-control" id="project_name" name="project_name" value="<?php echo htmlspecialchars($projectName ?? ''); ?>" required>
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<textarea class="form-control" id="description" name="description" rows="4"><?php echo htmlspecialchars($description ?? ''); ?></textarea>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="email" class="form-label">Contact Email</label>
<input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($email ?? ''); ?>">
</div>
<div class="col-md-6 mb-3">
<label for="links" class="form-label">Links (Comma separated)</label>
<input type="text" class="form-control" id="links" name="links" value="<?php echo htmlspecialchars($links ?? ''); ?>" placeholder="https://example1.com, https://example2.com">
</div>
</div>
<div id="additional_fields">
<!-- Additional fields will be loaded here based on domain selection -->
</div>
<div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
<button type="reset" class="btn btn-outline-secondary">
<i class="fas fa-undo me-1"></i> Reset
</button>
<button type="submit" class="btn btn-primary">
<i class="fas fa-save me-1"></i> Add Project
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to load additional fields based on domain selection
function loadAdditionalFields() {
const domainSelect = document.getElementById('domain');
const additionalFieldsContainer = document.getElementById('additional_fields');
const selectedDomain = domainSelect.value;
if (!selectedDomain) {
additionalFieldsContainer.innerHTML = '';
return;
}
// Show loading indicator
additionalFieldsContainer.innerHTML = '<div class="text-center my-3"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></div>';
// Use AJAX to get table structure
fetch('ajax/get_domain_fields.php?domain=' + selectedDomain)
.then(response => response.json())
.then(data => {
let html = '<h5 class="mt-4 mb-3">Additional Fields</h5>';
if (data.error) {
html = `<div class="alert alert-danger mt-3">${data.error}</div>`;
} else if (data.fields && data.fields.length > 0) {
data.fields.forEach(field => {
// Skip standard fields we already have in the form
if (['Project_ID', 'Domain_ID', 'Project_Name', 'H/S', 'Description', 'Email', 'Links'].includes(field.name)) {
return;
}
html += `
<div class="mb-3">
<label for="additional_${field.name}" class="form-label">${field.name}</label>
<input type="text" class="form-control" id="additional_${field.name}" name="additional_${field.name}"
value="${field.value || ''}">
</div>`;
});
} else {
html = '<div class="alert alert-info mt-3">No additional fields found for this domain.</div>';
}
additionalFieldsContainer.innerHTML = html;
})
.catch(error => {
additionalFieldsContainer.innerHTML = `<div class="alert alert-danger mt-3">Error loading fields: ${error.message}</div>`;
});
}
// Initialize
const domainSelect = document.getElementById('domain');
domainSelect.addEventListener('change', loadAdditionalFields);
// Load fields if domain is already selected (e.g., after form validation failure)
if (domainSelect.value) {
loadAdditionalFields();
}
});
</script>
<?php
// Include footer
include 'includes/footer.php';
// Close connection
$conn->close();
?>