Hola a todos, hoy os dejo una serie de ejercicios de AJAX de Javascript para practicar todo aquello que hemos explicado en anteriores posts.
Todos los ejercicios que proponemos están resueltos en este mismo post, intenta hacerlo por ti mismo y si te quedas atascado puedes mirar la solución. Recuerda, que no tiene por que estar igual tu solución con la del post, el objetivo es que aprendas no que me copies la solución.
Si tienes alguna duda, recuerda que puedes consultarnos escribiendo un comentario en este post o enviándonos un e-mail a administrador@discoduroderoer.es
1. Crear una conexion de base de datos con mysql. Comprobar que funciona.
— index.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 |
require_once "conexion.php"; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>BD1</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> $resultado = $conexion->query("select * from pokemon"); while($row = mysqli_fetch_array($resultado)){ echo $row["nombre"]." "; } ?> </body> </html> |
— conexion.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
define("HOST_DB", "localhost"); define("USER_DB", "root"); define("PASS_DB", ""); define("NAME_DB", "pokemondb"); $conexion = new mysqli( constant("HOST_DB"), constant("USER_DB"), constant("PASS_DB"), constant("NAME_DB") ); ?> |
2. Mostrar una tabla con los cursos que hay en la tabla de cursos.
— conexion.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
define("HOST_DB", "localhost"); define("USER_DB", "root"); define("PASS_DB", ""); define("NAME_DB", "academia_idiomas"); $conexion = new mysqli( constant("HOST_DB"), constant("USER_DB"), constant("PASS_DB"), constant("NAME_DB") ); ?> |
— index.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 |
require "conexion.php"; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="estilos.css"> </head> <body> $sql = "select * from cursos"; $resultados = mysqli_query($conexion, $sql); $num_filas = mysqli_num_rows($resultados); if($num_filas === 0){ ?> <p>No hay cursos disponibles</p> }else{ ?> <button href="#">Añadir nuevo curso</button> <table> <tr> <th>Código</th> <th>Nombre</th> <th>Horario</th> <th>Fecha inicio</th> <th>Fecha fin</th> <th>Precio</th> </tr> while($fila = mysqli_fetch_assoc($resultados)){ echo " echo " ".$fila['codigo']." | "; echo " ".$fila['nombre']." | "; echo " ".$fila['horario']." | "; echo " ".$fila['fecha_inicio']." | "; echo " ".$fila['fecha_fin']." | "; echo " ".$fila['precio']." | "; echo " } ?> </table> } ?> </body> </html> |
— estilos.css
|
1 2 3 |
table, th, td{ border: 1px solid #000; } |
— academia_idiomas.sql
|
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 |
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; CREATE DATABASE IF NOT EXISTS `academia_idiomas` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE `academia_idiomas`; CREATE TABLE `cursos` ( `codigo` int(11) NOT NULL, `nombre` varchar(30) COLLATE utf8_bin DEFAULT NULL, `horario` varchar(11) COLLATE utf8_bin DEFAULT NULL, `fecha_inicio` date DEFAULT NULL, `fecha_fin` date DEFAULT NULL, `precio` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; INSERT INTO `cursos` (`codigo`, `nombre`, `horario`, `fecha_inicio`, `fecha_fin`, `precio`) VALUES (1, 'Ingles', '08:00-14:00', '2019-03-01', '2019-03-29', 250.5), (2, 'Frances', '16:00-19:00', '2019-04-01', '2019-04-29', 200); ALTER TABLE `cursos` ADD PRIMARY KEY (`codigo`); ALTER TABLE `cursos` MODIFY `codigo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; COMMIT; |
3. Crear el formulario para añadir un curso.
— conexion.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
define("HOST_DB", "localhost"); define("USER_DB", "root"); define("PASS_DB", ""); define("NAME_DB", "academia_idiomas"); $conexion = new mysqli( constant("HOST_DB"), constant("USER_DB"), constant("PASS_DB"), constant("NAME_DB") ); ?> |
— index.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 69 70 71 72 73 74 75 76 77 78 |
require "conexion.php"; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="estilos.css"> </head> <body> session_start(); if (isset($_SESSION['curso_insertado'])) { echo ' ' . $_SESSION['curso_insertado'] . ''; unset($_SESSION['curso_insertado']); } $sql = "select * from cursos"; $resultados = mysqli_query($conexion, $sql); $num_filas = mysqli_num_rows($resultados); if ($num_filas === 0) { ?> <p>No hay cursos disponibles</p> } else { ?> <button><a href="form-aniadir-curso.php">Añadir nuevo curso</a></button> <table> <tr> <th>Código</th> <th>Nombre</th> <th>Horario</th> <th>Fecha inicio</th> <th>Fecha fin</th> <th>Precio</th> </tr> while ($fila = mysqli_fetch_assoc($resultados)) { echo " echo " " . $fila['codigo'] . " | "; echo " " . $fila['nombre'] . " | "; echo " " . $fila['horario'] . " | "; echo " " . $fila['fecha_inicio'] . " | "; echo " " . $fila['fecha_fin'] . " | "; echo " " . $fila['precio'] . " | "; echo " } ?> </table> } ?> </body> </html> |
— form-aniadir.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 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="estilos.css"> <title>Añadir curso</title> </head> <body> <h1>Añadir curso</h1> session_start(); if(isset($_SESSION['curso_no_insertado'])){ echo ' ' .$_SESSION['curso_no_insertado'].''; unset($_SESSION['curso_no_insertado']); } ?> <form action="aniadir-curso.php" method="post"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" required> <label for="horario">Horario</label> <input type="text" name="horario" id="horario" required> <label for="finicial">Fecha inicial</label> <input type="date" name="finicial" id="finicial" required> <label for="ffin">Fecha fin</label> <input type="date" name="ffin" id="ffin" required> <label for="precio">Precio</label> <input type="text" name="precio" id="precio" required> <input type="submit" name="enviar" value="Enviar"> </form> </body> </html> |
— aniadir-curso.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
require 'conexion.php'; session_start(); $nombre = $_POST['nombre']; $horario = $_POST['horario']; $finicial = $_POST['finicial']; $ffin = $_POST['ffin']; $precio = $_POST['precio']; $sql = "insert into cursos values(null, '".$nombre."', '".$horario."', '".$finicial."', '".$ffin."', ".$precio.")"; if(mysqli_query($conexion, $sql)){ $_SESSION['curso_insertado']="El curso se ha insertado correctamente"; header("Location: index.php"); }else{ $_SESSION['curso_no_insertado']="El curso no se ha insertado correctamente"; header("Location: form-aniadir-curso.php"); } ?> |
— estilos.css
|
1 2 3 4 5 6 7 |
table, th, td{ border: 1px solid #000; } label, input{ display: block; } |
— academia_idiomas.sql
|
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 |
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; CREATE DATABASE IF NOT EXISTS `academia_idiomas` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE `academia_idiomas`; CREATE TABLE `cursos` ( `codigo` int(11) NOT NULL, `nombre` varchar(30) COLLATE utf8_bin DEFAULT NULL, `horario` varchar(11) COLLATE utf8_bin DEFAULT NULL, `fecha_inicio` date DEFAULT NULL, `fecha_fin` date DEFAULT NULL, `precio` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; INSERT INTO `cursos` (`codigo`, `nombre`, `horario`, `fecha_inicio`, `fecha_fin`, `precio`) VALUES (1, 'Ingles', '08:00-14:00', '2019-03-01', '2019-03-29', 250.5), (2, 'Frances', '16:00-19:00', '2019-04-01', '2019-04-29', 200); ALTER TABLE `cursos` ADD PRIMARY KEY (`codigo`); ALTER TABLE `cursos` MODIFY `codigo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; COMMIT; |
4. Valida la insercion de un curso.
— index.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 69 70 71 72 73 74 75 76 77 78 |
require "conexion.php"; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="estilos.css"> </head> <body> session_start(); if (isset($_SESSION['curso_insertado'])) { echo ' ' . $_SESSION['curso_insertado'] . ''; unset($_SESSION['curso_insertado']); } $sql = "select * from cursos"; $resultados = mysqli_query($conexion, $sql); $num_filas = mysqli_num_rows($resultados); if ($num_filas === 0) { ?> <p>No hay cursos disponibles</p> } else { ?> <button><a href="form-aniadir-curso.php">Añadir nuevo curso</a></button> <table> <tr> <th>Código</th> <th>Nombre</th> <th>Horario</th> <th>Fecha inicio</th> <th>Fecha fin</th> <th>Precio</th> </tr> while ($fila = mysqli_fetch_assoc($resultados)) { echo " echo " " . $fila['codigo'] . " | "; echo " " . $fila['nombre'] . " | "; echo " " . $fila['horario'] . " | "; echo " " . $fila['fecha_inicio'] . " | "; echo " " . $fila['fecha_fin'] . " | "; echo " " . $fila['precio'] . " | "; echo " } ?> </table> } ?> </body> </html> |
— conexion.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
define("HOST_DB", "localhost"); define("USER_DB", "root"); define("PASS_DB", ""); define("NAME_DB", "academia_idiomas"); $conexion = new mysqli( constant("HOST_DB"), constant("USER_DB"), constant("PASS_DB"), constant("NAME_DB") ); ?> |
— form-aniadir-curso.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 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="estilos.css"> <title>Añadir curso</title> </head> <body> <h1>Añadir curso</h1> session_start(); if(isset($_SESSION['curso_no_insertado'])){ echo ' ' .$_SESSION['curso_no_insertado'].''; unset($_SESSION['curso_no_insertado']); } ?> <form action="aniadir-curso.php" method="post"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" required> <label for="horario">Horario</label> <input type="text" pattern="([01]?[0-9]|2[0-3]):[0-5][0-9]-([01]?[0-9]|2[0-3]):[0-5][0-9]" name="horario" id="horario" required> <label for="finicial">Fecha inicial</label> <input type="date" name="finicial" id="finicial" required> <label for="ffin">Fecha fin</label> <input type="date" name="ffin" id="ffin" required> <label for="precio">Precio</label> <input type="text" name="precio" id="precio" required> <input type="submit" name="enviar" value="Enviar"> </form> </body> </html> |
— aniadir-curso.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 |
require 'conexion.php'; session_start(); $nombre = $_POST['nombre']; $horario = $_POST['horario']; $finicial = $_POST['finicial']; $ffin = $_POST['ffin']; $precio = $_POST['precio']; $errores = ''; $sql = "select * from cursos where trim(upper(nombre)) = trim(upper('".$nombre."'))"; $resultado = mysqli_query($conexion, $sql); $filas = mysqli_num_rows($resultado); if($filas > 0){ $errores .= '- El curso con ese nombre existe. '; } if($finicial > $ffin){ $errores .= '- La fecha inicial no puede ser mayor que la de fin. '; } if(is_numeric($precio)){ if($precio < 0){ $errores .= '- El precio debe ser positivo. '; } }else{ $errores .= '- El precio debe ser un número. '; } if(empty($errores)){ $sql = "insert into cursos values(null, '".$nombre."', '".$horario."', '".$finicial."', '".$ffin."', ".$precio.")"; if(mysqli_query($conexion, $sql)){ $_SESSION['curso_insertado']="El curso se ha insertado correctamente"; header("Location: index.php"); }else{ $_SESSION['curso_no_insertado']= mysqli_error($conexion); header("Location: form-aniadir-curso.php"); } }else{ $_SESSION['curso_no_insertado']= $errores; header("Location: form-aniadir-curso.php"); } ?> |
— estilos.css
|
1 2 3 4 5 6 7 |
table, th, td{ border: 1px solid #000; } label, input{ display: block; } |
— academia_idiomas.sql
|
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 |
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; CREATE DATABASE IF NOT EXISTS `academia_idiomas` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE `academia_idiomas`; CREATE TABLE `cursos` ( `codigo` int(11) NOT NULL, `nombre` varchar(30) COLLATE utf8_bin DEFAULT NULL, `horario` varchar(11) COLLATE utf8_bin DEFAULT NULL, `fecha_inicio` date DEFAULT NULL, `fecha_fin` date DEFAULT NULL, `precio` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; INSERT INTO `cursos` (`codigo`, `nombre`, `horario`, `fecha_inicio`, `fecha_fin`, `precio`) VALUES (1, 'Ingles', '08:00-14:00', '2019-03-01', '2019-03-29', 250.5), (2, 'Frances', '16:00-19:00', '2019-04-01', '2019-04-29', 200); ALTER TABLE `cursos` ADD PRIMARY KEY (`codigo`); ALTER TABLE `cursos` MODIFY `codigo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; COMMIT; |
5. Edita un curso.
— index.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 69 70 71 72 73 74 75 76 77 78 79 |
require "conexion.php"; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="estilos.css"> </head> <body> session_start(); if (isset($_SESSION['curso_correcto'])) { echo ' ' . $_SESSION['curso_correcto'] . ''; unset($_SESSION['curso_correcto']); } $sql = "select * from cursos"; $resultados = mysqli_query($conexion, $sql); $num_filas = mysqli_num_rows($resultados); if ($num_filas === 0) { ?> <p>No hay cursos disponibles</p> } else { ?> <button><a href="form-curso.php">Añadir nuevo curso</a></button> <table> <tr> <th>Código</th> <th>Nombre</th> <th>Horario</th> <th>Fecha inicio</th> <th>Fecha fin</th> <th>Precio</th> </tr> while ($fila = mysqli_fetch_assoc($resultados)) { echo " echo " " . $fila['codigo'] . " | "; echo " " . $fila['nombre'] . " | "; echo " " . $fila['horario'] . " | "; echo " " . $fila['fecha_inicio'] . " | "; echo " " . $fila['fecha_fin'] . " | "; echo " " . $fila['precio'] . " | "; echo " } ?> </table> } ?> </body> </html> |
— conexion.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
define("HOST_DB", "localhost"); define("USER_DB", "root"); define("PASS_DB", ""); define("NAME_DB", "academia_idiomas"); $conexion = new mysqli( constant("HOST_DB"), constant("USER_DB"), constant("PASS_DB"), constant("NAME_DB") ); ?> |
— form-curso.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 69 70 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="estilos.css"> <title>Añadir curso</title> </head> <body> session_start(); if (isset($_SESSION['curso_no_correcto'])) { echo ' ' . $_SESSION['curso_no_correcto'] . ''; unset($_SESSION['curso_no_correcto']); } if (isset($_GET['idcurso'])) { require 'conexion.php'; $id = $_GET['idcurso']; $sql = "select * from cursos where codigo = " . $id; $resultado = mysqli_query($conexion, $sql); $curso = mysqli_fetch_assoc($resultado); } ?> <h1> if(isset($curso)){ echo 'Editar curso'; }else{ echo 'Añadir curso'; } ?> </h1> <form action="registro-curso.php" method="post"> <input type="hidden" name="codigo" value=" if(isset($curso)){ echo $curso['codigo']; } ?>"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" required value=" if(isset($curso)){ echo $curso['nombre']; } ?>"> <label for="horario">Horario</label> <input type="text" pattern="([01]?[0-9]|2[0-3]):[0-5][0-9]-([01]?[0-9]|2[0-3]):[0-5][0-9]" name="horario" id="horario" required value=" if(isset($curso)){ echo $curso['horario']; } ?>"> <label for="finicial">Fecha inicial</label> <input type="date" name="finicial" id="finicial" required value=" if(isset($curso)){ echo $curso['fecha_inicial']; } ?>"> <label for="ffin">Fecha fin</label> <input type="date" name="ffin" id="ffin" required value=" if(isset($curso)){ echo $curso['fecha_fin']; } ?>"> <label for="precio">Precio</label> <input type="text" name="precio" id="precio" required value=" if(isset($curso)){ echo $curso['precio']; } ?>"> <input type="submit" name="enviar" value="Enviar"> </form> </body> </html> |
— registro-curso.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 69 70 |
require 'conexion.php'; session_start(); $codigo = $_POST['codigo']; $nombre = $_POST['nombre']; $horario = $_POST['horario']; $finicial = $_POST['finicial']; $ffin = $_POST['ffin']; $precio = $_POST['precio']; $errores = ''; if(empty($codigo)){ $sql = "select * from cursos where trim(upper(nombre)) = trim(upper('".$nombre."'))"; }else{ $sql = "select * from cursos where codigo != ".$codigo." and trim(upper(nombre)) = trim(upper('".$nombre."'))"; } $resultado = mysqli_query($conexion, $sql); $filas = mysqli_num_rows($resultado); if($filas > 0){ $errores .= '- El curso con ese nombre existe. '; } if($finicial > $ffin){ $errores .= '- La fecha inicial no puede ser mayor que la de fin. '; } if(is_numeric($precio)){ if($precio < 0){ $errores .= '- El precio debe ser positivo. '; } }else{ $errores .= '- El precio debe ser un número. '; } if(empty($errores)){ if(empty($codigo)){ $sql = "insert into cursos values"; $sql .= "(null, '".$nombre."', '".$horario."', '".$finicial."', '".$ffin."', ".$precio.")"; }else{ $sql = "update cursos set nombre='".$nombre."',"; $sql .= "horario='".$horario."', fecha_inicio='".$finicial."',"; $sql .= "fecha_fin='".$ffin."', precio=".$precio." "; $sql .= "where codigo = ".$codigo; } if(mysqli_query($conexion, $sql)){ if(empty($codigo)){ $_SESSION['curso_correcto']="El curso se ha insertado correctamente"; }else{ $_SESSION['curso_correcto']="El curso se ha actualizado correctamente"; } header("Location: index.php"); }else{ $_SESSION['curso_no_correcto']= mysqli_error($conexion); header("Location: form-curso.php"); } }else{ $_SESSION['curso_no_correcto']= $errores; header("Location: form-curso.php"); } |
— estilos.css
|
1 2 3 4 5 6 7 |
table, th, td{ border: 1px solid #000; } label, input{ display: block; } |
— academia_idiomas.sql
|
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 |
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; CREATE DATABASE IF NOT EXISTS `academia_idiomas` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE `academia_idiomas`; CREATE TABLE `cursos` ( `codigo` int(11) NOT NULL, `nombre` varchar(30) COLLATE utf8_bin DEFAULT NULL, `horario` varchar(11) COLLATE utf8_bin DEFAULT NULL, `fecha_inicio` date DEFAULT NULL, `fecha_fin` date DEFAULT NULL, `precio` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; INSERT INTO `cursos` (`codigo`, `nombre`, `horario`, `fecha_inicio`, `fecha_fin`, `precio`) VALUES (1, 'Ingles', '08:00-14:00', '2019-03-01', '2019-03-29', 250.5), (2, 'Frances', '16:00-19:00', '2019-04-01', '2019-04-29', 200); ALTER TABLE `cursos` ADD PRIMARY KEY (`codigo`); ALTER TABLE `cursos` MODIFY `codigo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; COMMIT; |
6. Borra un curso.
— index.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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
require "conexion.php"; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="estilos.css"> </head> <body> session_start(); if (isset($_SESSION['curso_correcto'])) { echo ' ' . $_SESSION['curso_correcto'] . ''; unset($_SESSION['curso_correcto']); } if (isset($_SESSION['cursos_borrados'])) { echo ' ' . $_SESSION['cursos_borrados'] . ''; unset($_SESSION['cursos_borrados']); } if (isset($_SESSION['cursos_no_borrados'])) { echo ' ' . $_SESSION['cursos_no_borrados'] . ''; unset($_SESSION['cursos_no_borrados']); } $sql = "select * from cursos"; $resultados = mysqli_query($conexion, $sql); $num_filas = mysqli_num_rows($resultados); if ($num_filas === 0) { ?> <p>No hay cursos disponibles</p> } else { ?> <button><a href="form-curso.php">Añadir nuevo curso</a></button> <form action="borrar-cursos.php" method="post"> <table> <tr> <th></th> <th>Código</th> <th>Nombre</th> <th>Horario</th> <th>Fecha inicio</th> <th>Fecha fin</th> <th>Precio</th> </tr> while ($fila = mysqli_fetch_assoc($resultados)) { echo " echo " ]."' /> | "; echo " " . $fila['codigo'] . " | "; echo " " . $fila['nombre'] . " | "; echo " " . $fila['horario'] . " | "; echo " " . $fila['fecha_inicio'] . " | "; echo " " . $fila['fecha_fin'] . " | "; echo " " . $fila['precio'] . " | "; echo " } ?> </table> <input type="submit" value="Borrar cursos seleccionados" /> </form> } ?> </body> </html> |
— form-curso.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 69 70 71 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="estilos.css"> <title>Añadir curso</title> </head> <body> session_start(); if(isset($_SESSION['curso_no_correcto'])){ echo ' ' .$_SESSION['curso_no_correcto'].''; unset($_SESSION['curso_no_correcto']); } if(isset($_GET['idcurso'])){ require 'conexion.php'; $id = $_GET['idcurso']; $sql = "select * from cursos where codigo = " .$id; $resultado = mysqli_query($conexion, $sql); $curso = mysqli_fetch_assoc($resultado); } ?> <h1> if(isset($codigo)){ echo 'Editar curso'; }else{ echo 'Añadir curso'; } ?></h1> <form action="registro-curso.php" method="post"> <input type="hidden" name="codigo" value=" if(isset($curso)){ echo $curso['codigo']; } ?>"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" required value=" if(isset($curso)){ echo $curso['nombre']; } ?>"> <label for="horario">Horario</label> <input type="text" pattern="([01]?[0-9]|2[0-3]):[0-5][0-9]-([01]?[0-9]|2[0-3]):[0-5][0-9]" name="horario" id="horario" required value=" if(isset($curso)){ echo $curso['horario']; } ?>"> <label for="finicial">Fecha inicial</label> <input type="date" name="finicial" id="finicial" required value=" if(isset($curso)){ echo $curso['fecha_inicio']; } ?>"> <label for="ffin">Fecha fin</label> <input type="date" name="ffin" id="ffin" required value=" if(isset($curso)){ echo $curso['fecha_fin']; } ?>"> <label for="precio">Precio</label> <input type="text" name="precio" id="precio" required value=" if(isset($curso)){ echo $curso['precio']; } ?>"> <input type="submit" name="enviar" value="Enviar"> </form> </body> </html> |
— registro-curso.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 69 70 71 72 73 74 |
require 'conexion.php'; session_start(); $codigo = $_POST['codigo']; $nombre = $_POST['nombre']; $horario = $_POST['horario']; $finicial = $_POST['finicial']; $ffin = $_POST['ffin']; $precio = $_POST['precio']; $errores = ''; if(!empty($codigo)){ $sql = "select * from cursos where codigo != ".$codigo." trim(upper(nombre)) = trim(upper('".$nombre."'))"; }else{ $sql = "select * from cursos where trim(upper(nombre)) = trim(upper('".$nombre."'))"; } $resultado = mysqli_query($conexion, $sql); $filas = mysqli_num_rows($resultado); if($filas > 0){ $errores .= '- El curso con ese nombre existe. '; } if($finicial > $ffin){ $errores .= '- La fecha inicial no puede ser mayor que la de fin. '; } if(is_numeric($precio)){ if($precio < 0){ $errores .= '- El precio debe ser positivo. '; } }else{ $errores .= '- El precio debe ser un número. '; } if(empty($errores)){ if(!empty($codigo)){ $sql = "update cursos set nombre='".$nombre."',"; $sql .= "horario='".$horario."', fecha_inicio='".$finicial."',"; $sql .= "fecha_fin='".$ffin."', precio=".$precio." "; $sql .= "where codigo = ".$codigo; }else{ $sql = "insert into cursos values"; $sql .= "(null, '".$nombre."', '".$horario."', '".$finicial."', '".$ffin."', ".$precio.")"; } if(mysqli_query($conexion, $sql)){ if(!empty($codigo)){ $_SESSION['curso_correcto']="El curso se ha actualizado correctamente"; }else{ $_SESSION['curso_correcto']="El curso se ha insertado correctamente"; } header("Location: index.php"); }else{ $_SESSION['curso_no_correcto']= mysqli_error($conexion); header("Location: form-curso.php"); } }else{ $_SESSION['curso_no_correcto']= $errores; header("Location: form-curso.php"); } ?> |
— estilos.css
|
1 2 3 4 5 6 7 |
table, th, td{ border: 1px solid #000; } label, input{ display: block; } |
— borrar-curso.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 |
session_start(); require 'conexion.php'; if(isset($_GET['idcurso'])){ $sql = "delete from cursos where codigo = " . $_GET['idcurso']; }else if(isset($_POST['selec_curso'])){ $sql = "delete from cursos where codigo in (" . join(",",$_POST['selec_curso']).")"; } if(isset($sql)){ if(mysqli_query($conexion, $sql)){ $_SESSION['cursos_borrados']="Cursos/s borrado/s con exito"; header("Location: index.php"); }else{ $_SESSION['cursos_no_borrados']="Hubo un problema al borrar: " . mysqli_error($conexion); header("Location: index.php"); } }else{ $_SESSION['cursos_no_borrados']="Debes seleccionar al menos un curso"; header("Location: index.php"); } ?> |
— academia_idiomas.sql
|
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 |
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; CREATE DATABASE IF NOT EXISTS `academia_idiomas` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE `academia_idiomas`; CREATE TABLE `cursos` ( `codigo` int(11) NOT NULL, `nombre` varchar(30) COLLATE utf8_bin DEFAULT NULL, `horario` varchar(11) COLLATE utf8_bin DEFAULT NULL, `fecha_inicio` date DEFAULT NULL, `fecha_fin` date DEFAULT NULL, `precio` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; INSERT INTO `cursos` (`codigo`, `nombre`, `horario`, `fecha_inicio`, `fecha_fin`, `precio`) VALUES (1, 'Ingles', '08:00-14:00', '2019-03-01', '2019-03-29', 250.5), (2, 'Frances', '16:00-19:00', '2019-04-01', '2019-04-29', 200); ALTER TABLE `cursos` ADD PRIMARY KEY (`codigo`); ALTER TABLE `cursos` MODIFY `codigo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; COMMIT; |
7. Añade alumnos a un curso. Se ha actualizado la base de datos.
–index.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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
require "conexion.php"; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="estilos.css"> </head> <body> session_start(); if (isset($_SESSION['curso_correcto'])) { echo ' ' . $_SESSION['curso_correcto'] . ''; unset($_SESSION['curso_correcto']); } if (isset($_SESSION['cursos_borrados'])) { echo ' ' . $_SESSION['cursos_borrados'] . ''; unset($_SESSION['cursos_borrados']); } if (isset($_SESSION['cursos_no_borrados'])) { echo ' ' . $_SESSION['cursos_no_borrados'] . ''; unset($_SESSION['cursos_no_borrados']); } if (isset($_SESSION['alumno_correcto'])) { echo $_SESSION['alumno_correcto']; unset($_SESSION['alumno_correcto']); } $sql = "select * from cursos"; $resultados = mysqli_query($conexion, $sql); $num_filas = mysqli_num_rows($resultados); if ($num_filas === 0) { ?> <p>No hay cursos disponibles</p> } else { ?> <button><a href="form-curso.php">Añadir nuevo curso</a></button> <button><a href="form-alumno.php">Añadir nuevo alumno</a></button> <form action="borrar-cursos.php" method="post"> <table> <tr> <th></th> <th>Código</th> <th>Nombre</th> <th>Horario</th> <th>Fecha inicio</th> <th>Fecha fin</th> <th>Precio</th> </tr> while ($fila = mysqli_fetch_assoc($resultados)) { echo " echo " ] . "' /> | "; echo " " . $fila['codigo'] . " | "; echo " " . $fila['nombre'] . " | "; echo " " . $fila['horario'] . " | "; echo " " . $fila['fecha_inicio'] . " | "; echo " " . $fila['fecha_fin'] . " | "; echo " " . $fila['precio'] . " | "; echo " } ?> </table> <input type="submit" value="Borrar cursos seleccionados" /> </form> } ?> </body> </html> |
— conexion.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
define("HOST_DB", "localhost"); define("USER_DB", "root"); define("PASS_DB", ""); define("NAME_DB", "academia_idiomas"); $conexion = new mysqli( constant("HOST_DB"), constant("USER_DB"), constant("PASS_DB"), constant("NAME_DB") ); ?> |
— form-curso.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 69 70 71 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="estilos.css"> <title>Añadir curso</title> </head> <body> session_start(); if(isset($_SESSION['curso_no_correcto'])){ echo ' ' .$_SESSION['curso_no_correcto'].''; unset($_SESSION['curso_no_correcto']); } if(isset($_GET['idcurso'])){ require 'conexion.php'; $id = $_GET['idcurso']; $sql = "select * from cursos where codigo = " .$id; $resultado = mysqli_query($conexion, $sql); $curso = mysqli_fetch_assoc($resultado); } ?> <h1> if(isset($codigo)){ echo 'Editar curso'; }else{ echo 'Añadir curso'; } ?></h1> <form action="registro-curso.php" method="post"> <input type="hidden" name="codigo" value=" if(isset($curso)){ echo $curso['codigo']; } ?>"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" required value=" if(isset($curso)){ echo $curso['nombre']; } ?>"> <label for="horario">Horario</label> <input type="text" pattern="([01]?[0-9]|2[0-3]):[0-5][0-9]-([01]?[0-9]|2[0-3]):[0-5][0-9]" name="horario" id="horario" required value=" if(isset($curso)){ echo $curso['horario']; } ?>"> <label for="finicial">Fecha inicial</label> <input type="date" name="finicial" id="finicial" required value=" if(isset($curso)){ echo $curso['fecha_inicio']; } ?>"> <label for="ffin">Fecha fin</label> <input type="date" name="ffin" id="ffin" required value=" if(isset($curso)){ echo $curso['fecha_fin']; } ?>"> <label for="precio">Precio</label> <input type="text" name="precio" id="precio" required value=" if(isset($curso)){ echo $curso['precio']; } ?>"> <input type="submit" name="enviar" value="Enviar"> </form> </body> </html> |
— registro-curso.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 69 70 71 72 73 74 |
require 'conexion.php'; session_start(); $codigo = $_POST['codigo']; $nombre = $_POST['nombre']; $horario = $_POST['horario']; $finicial = $_POST['finicial']; $ffin = $_POST['ffin']; $precio = $_POST['precio']; $errores = ''; if(!empty($codigo)){ $sql = "select * from cursos where codigo != ".$codigo." trim(upper(nombre)) = trim(upper('".$nombre."'))"; }else{ $sql = "select * from cursos where trim(upper(nombre)) = trim(upper('".$nombre."'))"; } $resultado = mysqli_query($conexion, $sql); $filas = mysqli_num_rows($resultado); if($filas > 0){ $errores .= '- El curso con ese nombre existe. '; } if($finicial > $ffin){ $errores .= '- La fecha inicial no puede ser mayor que la de fin. '; } if(is_numeric($precio)){ if($precio < 0){ $errores .= '- El precio debe ser positivo. '; } }else{ $errores .= '- El precio debe ser un número. '; } if(empty($errores)){ if(!empty($codigo)){ $sql = "update cursos set nombre='".$nombre."',"; $sql .= "horario='".$horario."', fecha_inicio='".$finicial."',"; $sql .= "fecha_fin='".$ffin."', precio=".$precio." "; $sql .= "where codigo = ".$codigo; }else{ $sql = "insert into cursos values"; $sql .= "(null, '".$nombre."', '".$horario."', '".$finicial."', '".$ffin."', ".$precio.")"; } if(mysqli_query($conexion, $sql)){ if(!empty($codigo)){ $_SESSION['curso_correcto']="El curso se ha actualizado correctamente"; }else{ $_SESSION['curso_correcto']="El curso se ha insertado correctamente"; } header("Location: index.php"); }else{ $_SESSION['curso_no_correcto']= mysqli_error($conexion); header("Location: form-curso.php"); } }else{ $_SESSION['curso_no_correcto']= $errores; header("Location: form-curso.php"); } ?> |
— borrar-curso.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 |
session_start(); require 'conexion.php'; if(isset($_GET['idcurso'])){ $sql = "delete from cursos where codigo = " . $_GET['idcurso']; }else if(isset($_POST['selec_curso'])){ $sql = "delete from cursos where codigo in (" . join(",",$_POST['selec_curso']).")"; } if(isset($sql)){ if(mysqli_query($conexion, $sql)){ $_SESSION['cursos_borrados']="Cursos/s borrado/s con exito"; header("Location: index.php"); }else{ $_SESSION['cursos_no_borrados']="Hubo un problema al borrar: " . mysqli_error($conexion); header("Location: index.php"); } }else{ $_SESSION['cursos_no_borrados']="Debes seleccionar al menos un curso"; header("Location: index.php"); } ?> |
— form-alumno.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 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Añadir alumno</title> </head> <body> <h1>Añadir alumno</h1> session_start(); if(isset($_SESSION['alumno_no_correcto'])){ echo $_SESSION['alumno_no_correcto']; unset($_SESSION['alumno_no_correcto']); } ?> <form action="aniadir-alumno.php" method="post"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" /> <label for="fecha">Fecha inscripcion</label> <input type="text" name="fecha" id="fecha" /> <label for="curso">Curso</label> <select name="curso" id="curso"> $sql = "select * from cursos"; require_once "conexion.php"; $resultado = mysqli_query($conexion, $sql); while($fila = mysqli_fetch_assoc($resultado)){ ?> <option value=" echo $fila['codigo'] ?>"> echo $fila['nombre'] ?></option> } ?> </select> <input type="submit" value="Añadir" /> </form> </body> </html> |
— aniadir-alumno.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
session_start(); require_once "conexion.php"; $nombre = $_POST['nombre']; $fecha = $_POST['fecha']; $curso = $_POST['curso']; $sql = "INSERT INTO alumnos VALUES(null, '$nombre', '$fecha', '$curso')"; if(mysqli_query($conexion, $sql)){ $_SESSION['alumno_correcto'] = 'El alumno se ha añadido correctamente'; header("Location: index.php"); }else{ $_SESSION['alumno_no_correcto'] = 'El alumno no se ha añadido correctamente'; header("Location: form-alumno.php"); } ?> |
— academia_idiomas.sql
|
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 |
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; CREATE DATABASE IF NOT EXISTS `academia_idiomas` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE `academia_idiomas`; CREATE TABLE `cursos` ( `codigo` int(11) NOT NULL, `nombre` varchar(30) COLLATE utf8_bin DEFAULT NULL, `horario` varchar(11) COLLATE utf8_bin DEFAULT NULL, `fecha_inicio` date DEFAULT NULL, `fecha_fin` date DEFAULT NULL, `precio` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; INSERT INTO `cursos` (`codigo`, `nombre`, `horario`, `fecha_inicio`, `fecha_fin`, `precio`) VALUES (1, 'Ingles', '08:00-14:00', '2019-03-01', '2019-03-29', 250.5), (2, 'Frances', '16:00-19:00', '2019-04-01', '2019-04-29', 200); ALTER TABLE `cursos` ADD PRIMARY KEY (`codigo`); ALTER TABLE `cursos` MODIFY `codigo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; COMMIT; |
8. Muestra los alumnos de un curso.
— index.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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
require "conexion.php"; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Cursos</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="estilos.css"> </head> <body> session_start(); if (isset($_SESSION['curso_correcto'])) { echo ' ' . $_SESSION['curso_correcto'] . ''; unset($_SESSION['curso_correcto']); } if (isset($_SESSION['cursos_borrados'])) { echo ' ' . $_SESSION['cursos_borrados'] . ''; unset($_SESSION['cursos_borrados']); } if (isset($_SESSION['cursos_no_borrados'])) { echo ' ' . $_SESSION['cursos_no_borrados'] . ''; unset($_SESSION['cursos_no_borrados']); } if (isset($_SESSION['alumno_correcto'])) { echo $_SESSION['alumno_correcto']; unset($_SESSION['alumno_correcto']); } $sql = "select * from cursos"; $resultados = mysqli_query($conexion, $sql); $num_filas = mysqli_num_rows($resultados); if ($num_filas === 0) { ?> <p>No hay cursos disponibles</p> } else { ?> <button><a href="form-curso.php">Añadir nuevo curso</a></button> <button><a href="form-alumno.php">Añadir nuevo alumno</a></button> <form action="borrar-cursos.php" method="post"> <table> <tr> <th></th> <th>Código</th> <th>Nombre</th> <th>Horario</th> <th>Fecha inicio</th> <th>Fecha fin</th> <th>Precio</th> </tr> while ($fila = mysqli_fetch_assoc($resultados)) { echo " echo " ] . "' /> | "; echo " " . $fila['codigo'] . " | "; echo " " . $fila['nombre'] . " | "; echo " " . $fila['horario'] . " | "; echo " " . $fila['fecha_inicio'] . " | "; echo " " . $fila['fecha_fin'] . " | "; echo " " . $fila['precio'] . " | "; echo " } ?> </table> <input type="submit" value="Borrar cursos seleccionados" /> </form> } ?> </body> </html> |
— conexion.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
define("HOST_DB", "localhost"); define("USER_DB", "root"); define("PASS_DB", ""); define("NAME_DB", "academia_idiomas"); $conexion = new mysqli( constant("HOST_DB"), constant("USER_DB"), constant("PASS_DB"), constant("NAME_DB") ); ?> |
— form-curso.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 69 70 71 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="estilos.css"> <title>Añadir curso</title> </head> <body> session_start(); if(isset($_SESSION['curso_no_correcto'])){ echo ' ' .$_SESSION['curso_no_correcto'].''; unset($_SESSION['curso_no_correcto']); } if(isset($_GET['idcurso'])){ require 'conexion.php'; $id = $_GET['idcurso']; $sql = "select * from cursos where codigo = " .$id; $resultado = mysqli_query($conexion, $sql); $curso = mysqli_fetch_assoc($resultado); } ?> <h1> if(isset($codigo)){ echo 'Editar curso'; }else{ echo 'Añadir curso'; } ?></h1> <form action="registro-curso.php" method="post"> <input type="hidden" name="codigo" value=" if(isset($curso)){ echo $curso['codigo']; } ?>"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" required value=" if(isset($curso)){ echo $curso['nombre']; } ?>"> <label for="horario">Horario</label> <input type="text" pattern="([01]?[0-9]|2[0-3]):[0-5][0-9]-([01]?[0-9]|2[0-3]):[0-5][0-9]" name="horario" id="horario" required value=" if(isset($curso)){ echo $curso['horario']; } ?>"> <label for="finicial">Fecha inicial</label> <input type="date" name="finicial" id="finicial" required value=" if(isset($curso)){ echo $curso['fecha_inicio']; } ?>"> <label for="ffin">Fecha fin</label> <input type="date" name="ffin" id="ffin" required value=" if(isset($curso)){ echo $curso['fecha_fin']; } ?>"> <label for="precio">Precio</label> <input type="text" name="precio" id="precio" required value=" if(isset($curso)){ echo $curso['precio']; } ?>"> <input type="submit" name="enviar" value="Enviar"> </form> </body> </html> |
— registro-curso.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 69 70 71 72 73 74 |
require 'conexion.php'; session_start(); $codigo = $_POST['codigo']; $nombre = $_POST['nombre']; $horario = $_POST['horario']; $finicial = $_POST['finicial']; $ffin = $_POST['ffin']; $precio = $_POST['precio']; $errores = ''; if(!empty($codigo)){ $sql = "select * from cursos where codigo != ".$codigo." trim(upper(nombre)) = trim(upper('".$nombre."'))"; }else{ $sql = "select * from cursos where trim(upper(nombre)) = trim(upper('".$nombre."'))"; } $resultado = mysqli_query($conexion, $sql); $filas = mysqli_num_rows($resultado); if($filas > 0){ $errores .= '- El curso con ese nombre existe. '; } if($finicial > $ffin){ $errores .= '- La fecha inicial no puede ser mayor que la de fin. '; } if(is_numeric($precio)){ if($precio < 0){ $errores .= '- El precio debe ser positivo. '; } }else{ $errores .= '- El precio debe ser un número. '; } if(empty($errores)){ if(!empty($codigo)){ $sql = "update cursos set nombre='".$nombre."',"; $sql .= "horario='".$horario."', fecha_inicio='".$finicial."',"; $sql .= "fecha_fin='".$ffin."', precio=".$precio." "; $sql .= "where codigo = ".$codigo; }else{ $sql = "insert into cursos values"; $sql .= "(null, '".$nombre."', '".$horario."', '".$finicial."', '".$ffin."', ".$precio.")"; } if(mysqli_query($conexion, $sql)){ if(!empty($codigo)){ $_SESSION['curso_correcto']="El curso se ha actualizado correctamente"; }else{ $_SESSION['curso_correcto']="El curso se ha insertado correctamente"; } header("Location: index.php"); }else{ $_SESSION['curso_no_correcto']= mysqli_error($conexion); header("Location: form-curso.php"); } }else{ $_SESSION['curso_no_correcto']= $errores; header("Location: form-curso.php"); } ?> |
— borrar-curso.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 |
session_start(); require 'conexion.php'; if(isset($_GET['idcurso'])){ $sql = "delete from cursos where codigo = " . $_GET['idcurso']; }else if(isset($_POST['selec_curso'])){ $sql = "delete from cursos where codigo in (" . join(",",$_POST['selec_curso']).")"; } if(isset($sql)){ if(mysqli_query($conexion, $sql)){ $_SESSION['cursos_borrados']="Cursos/s borrado/s con exito"; header("Location: index.php"); }else{ $_SESSION['cursos_no_borrados']="Hubo un problema al borrar: " . mysqli_error($conexion); header("Location: index.php"); } }else{ $_SESSION['cursos_no_borrados']="Debes seleccionar al menos un curso"; header("Location: index.php"); } ?> |
— form-alumno.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 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Añadir alumno</title> </head> <body> <h1>Añadir alumno</h1> session_start(); if(isset($_SESSION['alumno_no_correcto'])){ echo $_SESSION['alumno_no_correcto']; unset($_SESSION['alumno_no_correcto']); } ?> <form action="aniadir-alumno.php" method="post"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" /> <label for="fecha">Fecha inscripcion</label> <input type="text" name="fecha" id="fecha" /> <label for="curso">Curso</label> <select name="curso" id="curso"> $sql = "select * from cursos"; require_once "conexion.php"; $resultado = mysqli_query($conexion, $sql); while($fila = mysqli_fetch_assoc($resultado)){ ?> <option value=" echo $fila['codigo'] ?>"> echo $fila['nombre'] ?></option> } ?> </select> <input type="submit" value="Añadir" /> </form> </body> </html> |
— aniadir-alumno.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
session_start(); require_once "conexion.php"; $nombre = $_POST['nombre']; $fecha = $_POST['fecha']; $curso = $_POST['curso']; $sql = "INSERT INTO alumnos VALUES(null, '$nombre', '$fecha', '$curso')"; if(mysqli_query($conexion, $sql)){ $_SESSION['alumno_correcto'] = 'El alumno se ha añadido correctamente'; header("Location: index.php"); }else{ $_SESSION['alumno_no_correcto'] = 'El alumno no se ha añadido correctamente'; header("Location: form-alumno.php"); } ?> |
— academia_idiomas.sql
|
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 |
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; CREATE DATABASE IF NOT EXISTS `academia_idiomas` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE `academia_idiomas`; CREATE TABLE `cursos` ( `codigo` int(11) NOT NULL, `nombre` varchar(30) COLLATE utf8_bin DEFAULT NULL, `horario` varchar(11) COLLATE utf8_bin DEFAULT NULL, `fecha_inicio` date DEFAULT NULL, `fecha_fin` date DEFAULT NULL, `precio` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; INSERT INTO `cursos` (`codigo`, `nombre`, `horario`, `fecha_inicio`, `fecha_fin`, `precio`) VALUES (1, 'Ingles', '08:00-14:00', '2019-03-01', '2019-03-29', 250.5), (2, 'Frances', '16:00-19:00', '2019-04-01', '2019-04-29', 200); ALTER TABLE `cursos` ADD PRIMARY KEY (`codigo`); ALTER TABLE `cursos` MODIFY `codigo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; COMMIT; |
9. -Conexión PDO
— index.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 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Ejemplo PDO</title> </head> <body> require "conexion.php"; $sql = "SELECT * FROM pokemon"; $resultados = $conexion->query($sql); $resultados->execute(); while($fila = $resultados->fetch(PDO::FETCH_OBJ)){ echo $fila->nombre." "; } ?> </body> </html> |
— conexion.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
$opciones = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"); define("HOST_DB", "localhost"); define("USER_DB", "root"); define("PASS_DB", ""); define("NAME_DB", "pokemondb"); try{ $conexion = new PDO( "mysql:host=".constant("HOST_DB").";dbname=".constant("NAME_DB"), constant("USER_DB"), constant("PASS_DB"), $opciones ); }catch(PDOException $e){ echo "Error: ". $e->getMessage(). " "; exit; } ?> |
Espero que os sea de ayuda. Si tenéis dudas, preguntad. Estamos para ayudarte.
Deja una respuesta