1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | < 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | <?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 } |