Sistema de Notas

Nível: Intermediário
Conceitos: Arrays, sessões, loops, funções, cálculo de médias

Estrutura de Arquivos

/notas/
├── index.php
└── style.css

2.1 Arquivo index.php

<?php
// index.php - Sistema de Notas de Alunos

session_start();

// Inicializa a lista de alunos na sessão
if (!isset($_SESSION['alunos'])) {
    $_SESSION['alunos'] = [];
}

// Ação: adicionar aluno
if (isset($_POST['acao']) && $_POST['acao'] === 'adicionar') {
    $nome = trim($_POST['nome'] ?? '');
    $nota1 = floatval(str_replace(',', '.', $_POST['nota1'] ?? 0));
    $nota2 = floatval(str_replace(',', '.', $_POST['nota2'] ?? 0));
    $nota3 = floatval(str_replace(',', '.', $_POST['nota3'] ?? 0));

    if (!empty($nome) && $nota1 >= 0 && $nota1 <= 10 && $nota2 >= 0 && $nota2 <= 10 && $nota3 >= 0 && $nota3 <= 10) {
        $_SESSION['alunos'][] = [
            'id' => uniqid(),
            'nome' => $nome,
            'notas' => [$nota1, $nota2, $nota3],
        ];
    }
    header('Location: index.php');
    exit;
}

// Ação: remover aluno
if (isset($_GET['remover'])) {
    $id = $_GET['remover'];
    foreach ($_SESSION['alunos'] as $key => $aluno) {
        if ($aluno['id'] === $id) {
            unset($_SESSION['alunos'][$key]);
            break;
        }
    }
    $_SESSION['alunos'] = array_values($_SESSION['alunos']);
    header('Location: index.php');
    exit;
}

// Ação: limpar todos
if (isset($_GET['limpar'])) {
    $_SESSION['alunos'] = [];
    header('Location: index.php');
    exit;
}

/**
 * Calcula a média de um aluno
 */
function calcularMedia($notas) {
    return array_sum($notas) / count($notas);
}

/**
 * Retorna a situação do aluno
 */
function getSituacao($media) {
    if ($media >= 7) {
        return ['Aprovado', '#10b981', '✅'];
    } elseif ($media >= 5) {
        return ['Recuperação', '#f59e0b', '⚠️'];
    } else {
        return ['Reprovado', '#ef4444', '❌'];
    }
}

/**
 * Calcula estatísticas da turma
 */
function getEstatisticas($alunos) {
    if (empty($alunos)) {
        return ['media' => 0, 'maior' => 0, 'menor' => 0, 'aprovados' => 0];
    }

    $medias = array_map(function($a) { return calcularMedia($a['notas']); }, $alunos);
    $aprovados = count(array_filter($medias, function($m) { return $m >= 7; }));

    return [
        'media' => array_sum($medias) / count($medias),
        'maior' => max($medias),
        'menor' => min($medias),
        'aprovados' => $aprovados,
    ];
}

$estatisticas = getEstatisticas($_SESSION['alunos']);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistema de Notas</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>📚 Sistema de Notas</h1>
        <p class="subtitle">Cadastre alunos e acompanhe o desempenho da turma</p>

        <!-- Estatísticas -->
        <?php if (count($_SESSION['alunos']) > 0): ?>
        <div class="stats">
            <div class="stat-card">
                <span class="stat-icon">👥</span>
                <div>
                    <div class="stat-number"><?php echo count($_SESSION['alunos']); ?></div>
                    <div class="stat-label">Alunos</div>
                </div>
            </div>
            <div class="stat-card">
                <span class="stat-icon">📊</span>
                <div>
                    <div class="stat-number"><?php echo number_format($estatisticas['media'], 2, ',', '.'); ?></div>
                    <div class="stat-label">Média da Turma</div>
                </div>
            </div>
            <div class="stat-card">
                <span class="stat-icon">🏆</span>
                <div>
                    <div class="stat-number"><?php echo number_format($estatisticas['maior'], 2, ',', '.'); ?></div>
                    <div class="stat-label">Maior Média</div>
                </div>
            </div>
            <div class="stat-card">
                <span class="stat-icon">✅</span>
                <div>
                    <div class="stat-number"><?php echo $estatisticas['aprovados']; ?></div>
                    <div class="stat-label">Aprovados</div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Formulário de cadastro -->
        <div class="form-card">
            <h3>➕ Cadastrar Novo Aluno</h3>
            <form method="POST" action="">
                <input type="hidden" name="acao" value="adicionar">
                
                <div class="form-group">
                    <label for="nome">👤 Nome do Aluno</label>
                    <input type="text" id="nome" name="nome" required placeholder="Digite o nome completo">
                </div>

                <div class="notas-group">
                    <div class="form-group">
                        <label for="nota1">Nota 1</label>
                        <input type="text" id="nota1" name="nota1" required placeholder="0 a 10">
                    </div>
                    <div class="form-group">
                        <label for="nota2">Nota 2</label>
                        <input type="text" id="nota2" name="nota2" required placeholder="0 a 10">
                    </div>
                    <div class="form-group">
                        <label for="nota3">Nota 3</label>
                        <input type="text" id="nota3" name="nota3" required placeholder="0 a 10">
                    </div>
                </div>

                <button type="submit" class="btn-primary">💾 Cadastrar Aluno</button>
            </form>
        </div>

        <!-- Lista de alunos -->
        <?php if (count($_SESSION['alunos']) > 0): ?>
            <div class="lista-header">
                <h3>📋 Lista de Alunos</h3>
                <a href="?limpar=1" class="btn-limpar" onclick="return confirm('Limpar toda a lista?')">
                    🗑️ Limpar Tudo
                </a>
            </div>

            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th>Aluno</th>
                            <th>Nota 1</th>
                            <th>Nota 2</th>
                            <th>Nota 3</th>
                            <th>Média</th>
                            <th>Situação</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($_SESSION['alunos'] as $aluno): 
                            $media = calcularMedia($aluno['notas']);
                            list($situacao, $cor, $icone) = getSituacao($media);
                        ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($aluno['nome']); ?></strong></td>
                            <td><?php echo number_format($aluno['notas'][0], 1, ',', '.'); ?></td>
                            <td><?php echo number_format($aluno['notas'][1], 1, ',', '.'); ?></td>
                            <td><?php echo number_format($aluno['notas'][2], 1, ',', '.'); ?></td>
                            <td>
                                <strong style="color: <?php echo $cor; ?>">
                                    <?php echo number_format($media, 2, ',', '.'); ?>
                                </strong>
                            </td>
                            <td>
                                <span class="badge" style="background: <?php echo $cor; ?>">
                                    <?php echo $icone . ' ' . $situacao; ?>
                                </span>
                            </td>
                            <td>
                                <a href="?remover=<?php echo $aluno['id']; ?>" 
                                   class="btn-remove"
                                   onclick="return confirm('Remover este aluno?')">❌</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="empty-state">
                <span>📭</span>
                <p>Nenhum aluno cadastrado. Adicione o primeiro!</p>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>

2.2 Arquivo style.css

/* style.css - Sistema de Notas */

:root {
    --primary: #3b82f6;
    --primary-dark: #2563eb;
    --gradient: linear-gradient(135deg, #3b82f6, #1e40af);
    --dark: #1e293b;
    --gray: #64748b;
    --light-gray: #e2e8f0;
    --bg: #f1f5f9;
    --white: #ffffff;
    --radius: 14px;
    --transition: all 0.3s ease;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', system-ui, sans-serif;
    background: var(--bg);
    min-height: 100vh;
    padding: 20px;
}

.container {
    max-width: 1000px;
    margin: 0 auto;
    background: var(--white);
    border-radius: var(--radius);
    padding: 40px;
    box-shadow: 0 10px 30px rgba(59, 130, 246, 0.1);
}

h1 {
    font-size: 2rem;
    color: var(--dark);
    margin-bottom: 8px;
    text-align: center;
}

.subtitle {
    text-align: center;
    color: var(--gray);
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 2px solid var(--light-gray);
}

/* Estatísticas */
.stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 15px;
    margin-bottom: 30px;
}

.stat-card {
    background: var(--bg);
    padding: 18px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    gap: 15px;
    transition: var(--transition);
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 20px rgba(0,0,0,0.05);
}

.stat-icon {
    font-size: 2rem;
}

.stat-number {
    font-size: 1.5rem;
    font-weight: 700;
    color: var(--primary);
}

.stat-label {
    font-size: 0.8rem;
    color: var(--gray);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

/* Formulário */
.form-card {
    background: var(--bg);
    padding: 25px;
    border-radius: var(--radius);
    margin-bottom: 30px;
}

.form-card h3 {
    color: var(--dark);
    margin-bottom: 20px;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    font-weight: 600;
    color: var(--dark);
    margin-bottom: 6px;
    font-size: 0.9rem;
}

.form-group input {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid var(--light-gray);
    border-radius: 8px;
    font-size: 1rem;
    transition: var(--transition);
    background: var(--white);
}

.form-group input:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
}

.notas-group {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
}

.btn-primary {
    width: 100%;
    padding: 14px;
    background: var(--gradient);
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: var(--transition);
    margin-top: 10px;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 25px rgba(59, 130, 246, 0.3);
}

/* Lista */
.lista-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    flex-wrap: wrap;
    gap: 10px;
}

.lista-header h3 {
    color: var(--dark);
}

.btn-limpar {
    background: rgba(239, 68, 68, 0.1);
    color: #ef4444;
    padding: 8px 16px;
    border-radius: 8px;
    text-decoration: none;
    font-size: 0.85rem;
    font-weight: 500;
    transition: var(--transition);
}

.btn-limpar:hover {
    background: #ef4444;
    color: white;
}

/* Tabela */
.table-wrapper {
    overflow-x: auto;
    border-radius: 12px;
    border: 1px solid var(--light-gray);
}

table {
    width: 100%;
    border-collapse: collapse;
}

table thead {
    background: var(--dark);
    color: white;
}

table th {
    padding: 14px 16px;
    text-align: left;
    font-size: 0.85rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

table td {
    padding: 12px 16px;
    border-bottom: 1px solid var(--light-gray);
    color: var(--dark);
    font-size: 0.95rem;
}

table tbody tr:last-child td {
    border-bottom: none;
}

table tbody tr:hover {
    background: rgba(59, 130, 246, 0.04);
}

.badge {
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
    white-space: nowrap;
}

.btn-remove {
    background: rgba(239, 68, 68, 0.1);
    color: #ef4444;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    transition: var(--transition);
}

.btn-remove:hover {
    background: #ef4444;
    color: white;
    transform: scale(1.1);
}

.empty-state {
    text-align: center;
    padding: 50px 20px;
    background: var(--bg);
    border-radius: var(--radius);
}

.empty-state span {
    font-size: 3rem;
    display: block;
    margin-bottom: 15px;
}

.empty-state p {
    color: var(--gray);
}

@media (max-width: 700px) {
    .container { padding: 20px; }
    h1 { font-size: 1.5rem; }
    .notas-group { grid-template-columns: 1fr; }
    table th, table td { padding: 10px 8px; font-size: 0.85rem; }
}