Esempio CRUD-Codice semplificato. [PHP]

PHP e SQL
PHP e SQL

<?php

// 1. CONNESSIONE (Sempre uguale)

$host = ‘localhost’; $db = ‘nome_db’; $user = ‘root’; $pass = ”;

try {

    $pdo = new PDO(“mysql:host=$host;dbname=$db;charset=utf8”, $user, $pass);

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

} catch (PDOException $e) { die(“Errore: ” . $e->getMessage()); }

// 2. OPERAZIONI (C.R.U.D.)

// Azione: CANCELLAZIONE

if (isset($_GET[‘del’])) {

    $pdo->prepare(“DELETE FROM tabella WHERE id=?”)->execute([$_GET[‘del’]]);

    header(“Location: index.php”); exit;

}

// Azione: SALVATAGGIO (Sia Insert che Update)

if (isset($_POST[‘save’])) {

    $id = $_POST[‘id’];

    $valore1 = $_POST[‘campo1’]; // Es. Nome

    $valore2 = $_POST[‘campo2’]; // Es. Quantità

    if (!empty($id)) {

        // UPDATE

        $sql = “UPDATE tabella SET campo1=?, campo2=? WHERE id=?”;

        $pdo->prepare($sql)->execute([$valore1, $valore2, $id]);

    } else {

        // INSERT

        $sql = “INSERT INTO tabella (campo1, campo2) VALUES (?,?)”;

        $pdo->prepare($sql)->execute([$valore1, $valore2]);

    }

    header(“Location: index.php”); exit;

}

// 3. RECUPERO DATI PER MODIFICA

$mod = null;

if (isset($_GET[‘edit’])) {

    $stmt = $pdo->prepare(“SELECT * FROM tabella WHERE id=?”);

    $stmt->execute([$_GET[‘edit’]]);

    $mod = $stmt->fetch();

}

// 4. LETTURA TOTALE

$dati = $pdo->query(“SELECT * FROM tabella ORDER BY id DESC”)->fetchAll();

?>

<!DOCTYPE html>

<html lang=”it”>

<head>

    <meta charset=”UTF-8″>

    <title>Prova Pratica B016</title>

    <style>

        /* CSS Minimo: Tabella e Form */

        table { width: 100%; border-collapse: collapse; margin-top: 20px; }

        th, td { border: 1px solid #ccc; padding: 10px; text-align: left; }

        th { background: #eee; }

        .btn { padding: 5px 10px; text-decoration: none; border-radius: 4px; color: white; }

        .edit { background: blue; } .del { background: red; }

    </style>

</head>

<body>

    <form method=”POST”>

        <input type=”hidden” name=”id” value=”<?= $mod[‘id’] ?? ” ?>”>

        <input type=”text” name=”campo1″ value=”<?= $mod[‘campo1’] ?? ” ?>” placeholder=”Nome” required>

        <input type=”number” name=”campo2″ value=”<?= $mod[‘campo2’] ?? ” ?>” placeholder=”Quantità” required>

        <button type=”submit” name=”save”><?= $mod ? ‘Aggiorna’ : ‘Inserisci’ ?></button>

        <?php if($mod): ?> <a href=”index.php”>Annulla</a> <?php endif; ?>

    </form>

    <table>

        <tr><th>ID</th><th>Campo 1</th><th>Campo 2</th><th>Azioni</th></tr>

        <?php foreach($dati as $r): ?>

        <tr>

            <td><?= $r[‘id’] ?></td>

            <td><?= htmlspecialchars($r[‘campo1’]) ?></td>

            <td><?= htmlspecialchars($r[‘campo2’]) ?></td>

            <td>

                <a href=”?edit=<?= $r[‘id’] ?>” class=”btn edit”>M</a>

                <a href=”?del=<?= $r[‘id’] ?>” class=”btn del” onclick=”return confirm(‘Sicuro?’)”>X</a>

            </td>

        </tr>

        <?php endforeach; ?>

    </table>

</body>

</html>

** Se puoi sostenere il mio lavoro, comprami un libro | Buy me a book! **
** ISCRIVITI ALLA NEWSLETTER ! **

About the Author

Sergio Mauri
Blogger, autore. Perito in Sistemi Informativi Aziendali, musicista e compositore, Laurea in Discipline storiche e filosofiche e in Filosofia. Premio speciale al Concorso Claudia Ruggeri nel 2007; terzo posto al Premio Igor Slavich nel 2020. Ha pubblicato con Terra d'Ulivi nel 2007 e nel 2011, con Hammerle Editori nel 2013 e 2014, con PGreco nel 2015 con Historica Edizioni e Alcova Letteraria nel 2022 con Silele Edizioni (La Tela Nera) nel 2023 e con Amazon Kdp nel 2024, 2025 e 2026.