actores.php
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <?php $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; ?> <form method="post"> <p>Nombre<input type="text" name="first_name"></p> <p>Apellidos<input type="text" name="last_name"></p> <input type="submit"> </form> <table> <tr><td>Id</td><td>Nombre</td><td>Apellido</td><td>Acciones</td> </tr> <?php try { $conn = new PDO("mysql:host=$server;dbname=$db;charset=UTF8", $user, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Insertar el actor SI me lo mandas //Recuperar los datos de POST $first_name = filter_input(INPUT_POST, "first_name", FILTER_SANITIZE_MAGIC_QUOTES); $last_name = filter_input(INPUT_POST, "last_name", FILTER_SANITIZE_MAGIC_QUOTES); $actor_id = filter_input(INPUT_POST, "actor_id", FILTER_SANITIZE_NUMBER_INT); //Comprobar que me han mandado datos if (!empty($first_name) && !empty($last_name)) { //Si me han mandado crear el SQL para insertar o actualizar if (empty($actor_id)) { $sql = "insert into actor(first_name,last_name) values ('$first_name','$last_name')"; } else { $sql = "update actor set first_name='$first_name', last_name='$last_name'" . " where actor_id=$actor_id"; } //Ejecutarlo if ($conn->exec($sql) > 0) { echo "Insertado el actor $first_name $last_name"; } } $borrar = filter_input(INPUT_GET, "borrar", FILTER_SANITIZE_NUMBER_INT); if (!empty($borrar)) { $sql = "delete from actor where actor_id=$borrar"; if ($conn->exec($sql) > 0) { echo "Borrado el actor $borrar"; } } //Muestra los actores $sql = "select * from actor"; $q = $conn->query($sql); while ($row = $q->fetch()) { ?> <tr><td><?= $row['actor_id'] ?></td> <td><?= $row['first_name'] ?></td> <td><?= $row['last_name'] ?></td> <td><a href="actor_editar.php?actor_id=<?= $row['actor_id'] ?>">Editar</a> <a href="?borrar=<?= $row['actor_id'] ?>">Borrar</a></td> </tr> <?php } } catch (Exception $e) { echo "Connection failed: " . $e->getMessage(); } ?> </table> </body> </html>
actor_editar.php
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <?php $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; try { $conn = new PDO("mysql:host=$server;dbname=$db;charset=UTF8", $user, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $actor_id= filter_input(INPUT_GET, "actor_id",FILTER_SANITIZE_NUMBER_INT); $sql="select * from actor where actor_id=$actor_id"; $q=$conn->query($sql); $actor=$q->fetch(); //print_r($actor); ?> <h2>Editar actor</h2> <form action="actores.php" method="post"> <p>Id: <input readonly type="text" name="actor_id" value="<?=$actor['actor_id']?>"></p> <p>Nombre: <input type="text" name="first_name" value="<?=$actor['first_name']?>"></p> <p>Apellido: <input type="text" name="last_name" value="<?=$actor['last_name']?>"></p> <input type="submit"> </form> <?php } catch (Exception $e) { echo "Connection failed: " . $e->getMessage(); } ?> </body> </html>