Categorías Sakila

 <h1>Categorías</h1>
        <?php
        require_once 'libreria.php';
        $category = filter_input(INPUT_GET, 'category', FILTER_SANITIZE_STRING);
        $category_id = filter_input(INPUT_GET, 'category_id', FILTER_VALIDATE_INT);
        if (!empty($category)) {
            insertarCategoria($category);
        }
        if(!empty($category_id)){
            borraCategoria($category_id);
        }
        ?>
        <form>
            Categoría: <input type="text" name="category">
            <input type="submit" class="btn btn-success">
        </form>
        <hr/>
        <?php
        listadoCategorias();
        ?>

libreria.php

<?php

function conectar() {
    $server = "localhost";
    $user = "root";
    $password = "";
    $db = "sakila";
    try {
        $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password, [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"]);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $conn;
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}

function insertarCategoria($name) {
    try {
        $conn = conectar();
        $st = $conn->prepare("insert into category (name) values (:name)");
        $st->execute(['name' => $name]);
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}

function borraCategoria($id) {
    try {
        $conn = conectar();
        $st = $conn->prepare("delete from category where category_id=:id");
        $st->execute(['id' => $id]);
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}
function getCategorias() {
    try {
        $conn = conectar();
        $st = $conn->prepare("select * from category");
        $st->execute();
        $categorias = $st->fetchAll();
        return $categorias;
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}



function listadoCategorias() {
    echo "hola";
    $categorias = getCategorias();
    ?>
    <table class="table">
        <tr><td>Id</td><td>Nombre</td><td>Acciones</td></tr>
        <?php
        foreach ($categorias as $categoria) {
            ?>
            <tr><td><?= $categoria['category_id'] ?></td>
                <td><?= $categoria['name'] ?></td>
                <td><a href="?category_id=<?= $categoria['category_id'] ?>">Borrar</a></td>
            </tr>
            <?php
        }
        ?>
    </table>
    <?php
}

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos