Commit 942cc6f9 authored by Alan Davide Bovo's avatar Alan Davide Bovo
Browse files

add code for basic project

parent 472447b6
Loading
Loading
Loading
Loading
Loading
+36 −88
Original line number Diff line number Diff line
# Registro-Elettronico



## Getting started

To make it easy for you to get started with GitLab, here's a list of recommended next steps.

Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!

## Add your files

* [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
* [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:

# Registro Elettronico Voti

Applicazione web in PHP per la gestione dei voti di uno studente, con salvataggio su database MySQL tramite PDO.

## Funzionalità
- Inserimento di voti con materia e valore (1-10)
- Visualizzazione tabellare dei voti inseriti
- Calcolo automatico del numero totale dei voti e della media
- Indicazione dello stato: "Promosso" (media ≥ 6) o "Rimandato" (media < 6)
- Possibilità di eliminare un voto

## Requisiti
- PHP >= 7.0
- MySQL
- Estensione PDO per MySQL
- Bootstrap 5 (CDN)

## Installazione
1. Clona o scarica il progetto nella tua cartella web.
2. Crea un database MySQL chiamato `registro_voti` e la tabella `voti` con la seguente struttura:

```sql
CREATE TABLE voti (
  id INT AUTO_INCREMENT PRIMARY KEY,
  materia VARCHAR(100) NOT NULL,
  voto INT NOT NULL,
  data_inserimento TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
cd existing_repo
git remote add origin https://biagio.ispascalcomandini.it/gitlab/ALANDAVIDE.BOVO/registro-elettronico.git
git branch -M main
git push -uf origin main
```

## Integrate with your tools

* [Set up project integrations](https://biagio.ispascalcomandini.it/gitlab/ALANDAVIDE.BOVO/registro-elettronico/-/settings/integrations)

## Collaborate with your team

* [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
* [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
* [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
* [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
* [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)

## Test and Deploy

Use the built-in continuous integration in GitLab.

* [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
* [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
* [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
* [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
* [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)

***

# Editing this README

When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.

## Suggestions for a good README

Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.

## Name
Choose a self-explaining name for your project.

## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.

## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.

## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.

## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.

## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.

## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.

## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.

## Contributing
State if you are open to contributions and what your requirements are for accepting them.

For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
3. Modifica il file `config.php` con i dati di accesso al tuo database.
4. Avvia il server web e accedi a `index.php`.

You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Motivazione tecnica
L'applicazione utilizza un database per garantire la persistenza e la consistenza dei dati, evitando i limiti delle variabili di sessione (dati temporanei e non condivisibili tra utenti/dispositivi diversi).

## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## Autore
Alandavide Bovo

## License
For open source projects, say how it is licensed.
---

## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
Per domande o segnalazioni, apri una issue o contatta l'autore.

config.php

0 → 100644
+27 −0
Original line number Diff line number Diff line
<?php
// Configurazione del database
// Scelta del database rispetto alle sessioni:
// Utilizzare un database garantisce la persistenza e la consistenza dei dati.
// I dati non vengono persi alla chiusura del browser e sono accessibili da più utenti e dispositivi.
// Questo evita duplicazioni, conflitti e perdita di dati che possono verificarsi usando solo le sessioni.
// Le sessioni sono temporanee e legate al singolo utente, mentre il database centralizza e protegge le informazioni.
$host = 'localhost';
$db   = 'registro_voti';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    // In un ambiente di produzione, non mostrare l'errore dettagliato all'utente
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>

index.php

0 → 100644
+192 −0
Original line number Diff line number Diff line
<?php
// Inclusione del file di configurazione per la connessione al database
require_once 'config.php';

// Variabile per mostrare messaggi di feedback all'utente
$message = '';

// Gestione dell'eliminazione del voto tramite richiesta POST
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_id'])) {
    $delete_id = intval($_POST['delete_id']); // Sicurezza: conversione in intero
    try {
        // Query parametrica per eliminare il voto selezionato
        $stmt = $pdo->prepare("DELETE FROM voti WHERE id = :id");
        $stmt->execute(['id' => $delete_id]);
        $message = "<div class='alert alert-success' role='alert'>Voto eliminato con successo!</div>";
    } catch (PDOException $e) {
        // Gestione dell'errore in caso di problemi con il database
        $message = "<div class='alert alert-danger' role='alert'>Errore nell'eliminazione: " . $e->getMessage() . "</div>";
    }
}

// Gestione dell'inserimento di un nuovo voto tramite richiesta POST
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['materia']) && isset($_POST['voto'])) {
    $materia = trim($_POST['materia']); // Rimozione spazi
    $voto = intval($_POST['voto']);     // Conversione in intero per sicurezza

    // Validazione dei dati inseriti
    if (!empty($materia) && $voto >= 1 && $voto <= 10) {
        try {
            // Query parametrica per inserire il nuovo voto
            $stmt = $pdo->prepare("INSERT INTO voti (materia, voto) VALUES (:materia, :voto)");
            $stmt->execute(['materia' => $materia, 'voto' => $voto]);
            $message = "<div class='alert alert-success' role='alert'>Voto inserito con successo!</div>";
        } catch (PDOException $e) {
            // Gestione dell'errore in caso di problemi con il database
            $message = "<div class='alert alert-danger' role='alert'>Errore nell'inserimento: " . $e->getMessage() . "</div>";
        }
    } else {
        // Messaggio di errore se i dati non sono validi
        $message = "<div class='alert alert-warning' role='alert'>Inserisci un voto valido (1-10) e il nome della materia.</div>";
    }
}

// Recupero di tutti i voti dal database, ordinati per data di inserimento decrescente
$stmt = $pdo->query("SELECT * FROM voti ORDER BY data_inserimento DESC");
$voti = $stmt->fetchAll();

// Calcolo del numero totale dei voti e della somma dei voti per la media
$sommaVoti = 0;
$numeroVoti = count($voti);

// Ciclo per sommare tutti i voti
foreach ($voti as $voto) {
    $sommaVoti += $voto['voto'];
}

// Calcolo della media aritmetica dei voti
$media = ($numeroVoti > 0) ? $sommaVoti / $numeroVoti : 0;

// Determinazione dello stato finale: Promosso o Rimandato
$stato = "";
$badgeClass = "";
if ($numeroVoti > 0) {
    if ($media >= 6) {
        $stato = "Promosso";
        $badgeClass = "bg-success";
    } else {
        $stato = "Rimandato";
        $badgeClass = "bg-danger";
    }
}
?>

<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestione Voti Studente</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- FontAwesome for Icons (Optional but nice) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { background-color: #f8f9fa; }
        .main-container { max-width: 800px; margin-top: 50px; }
        .card { box-shadow: 0 4px 8px rgba(0,0,0,0.1); border: none; }
        .card-header { background-color: #4a90e2; color: white; font-weight: bold; }
        .table-hover tbody tr:hover { background-color: #f1f1f1; }
        .summary-card { background-color: #e9ecef; }
    </style>
</head>
<body>

<div class="container main-container">
    <div class="card mb-4">
        <div class="card-header text-center">
            <h3><i class="fas fa-graduation-cap"></i> Registro Elettronico Voti</h3>
        </div>
        <div class="card-body">
            
            <?= $message ?>

            <form method="POST" action="" class="row g-3">
                <div class="col-md-7">
                    <label for="materia" class="form-label">Materia</label>
                    <input type="text" class="form-control" id="materia" name="materia" placeholder="Es. Matematica" required>
                </div>
                <div class="col-md-3">
                    <label for="voto" class="form-label">Voto</label>
                    <input type="number" class="form-control" id="voto" name="voto" placeholder="1-10" min="1" max="10" required>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100"><i class="fas fa-plus"></i> Aggiungi</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <h4 class="card-title mb-3">Riepilogo Voti</h4>
            
            <?php if ($numeroVoti > 0): ?>
                <div class="table-responsive">
                    <table class="table table-striped table-hover align-middle">
                        <thead class="table-dark">
                            <tr>
                                <th>Materia</th>
                                <th class="text-center">Voto</th>
                                <th class="text-end">Inserito il</th>
                                <th class="text-end">Azioni</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($voti as $row): ?>
                                <tr>
                                    <td><?= htmlspecialchars($row['materia']) ?></td>
                                    <td class="text-center">
                                        <span class="badge rounded-pill <?= $row['voto'] >= 6 ? 'bg-success' : 'bg-danger' ?>">
                                            <?= htmlspecialchars($row['voto']) ?>
                                        </span>
                                    </td>
                                    <td class="text-end text-muted small"><?= date('d/m/Y H:i', strtotime($row['data_inserimento'])) ?></td>
                                    <td class="text-end">
                                        <form method="POST" action="" style="display:inline;">
                                            <input type="hidden" name="delete_id" value="<?= $row['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Sei sicuro di voler eliminare questo voto?');">
                                                <i class="fas fa-trash"></i> Elimina
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="card summary-card mt-3">
                    <div class="card-body text-center">
                        <div class="row">
                            <div class="col-md-4">
                                <h5>Totale Voti</h5>
                                <p class="display-6"><?= $numeroVoti ?></p>
                            </div>
                            <div class="col-md-4">
                                <h5>Media</h5>
                                <p class="display-6 <?= $media >= 6 ? 'text-success' : 'text-danger' ?>">
                                    <?= number_format($media, 2) ?>
                                </p>
                            </div>
                            <div class="col-md-4">
                                <h5>Esito</h5>
                                <span class="badge <?= $badgeClass ?> p-3 fs-5"><?= $stato ?></span>
                            </div>
                        </div>
                    </div>
                </div>

            <?php else: ?>
                <div class="alert alert-info text-center" role="alert">
                    <i class="fas fa-info-circle"></i> Nessun voto inserito ancora. Inizia aggiungendone uno sopra!
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Bootstrap JS (Optional) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

install.sql

0 → 100644
+9 −0
Original line number Diff line number Diff line
CREATE DATABASE IF NOT EXISTS registro_voti;
USE registro_voti;

CREATE TABLE IF NOT EXISTS voti (
    id INT AUTO_INCREMENT PRIMARY KEY,
    materia VARCHAR(255) NOT NULL,
    voto INT NOT NULL CHECK (voto >= 1 AND voto <= 10),
    data_inserimento TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);