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.
Spoiler Inside | SelectShow> |
---|---|
— index.php <?php 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> <?php $resultado = $conexion->query("select * from pokemon"); while($row = mysqli_fetch_array($resultado)){ echo $row["nombre"]."<br/>"; } ?> </body> </html> — conexion.php <?php 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.
Spoiler Inside | SelectShow> |
---|---|
— conexion.php <?php 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 <?php 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> <?php $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> <?php }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> <?php while($fila = mysqli_fetch_assoc($resultados)){ echo "<tr>"; echo "<td>".$fila['codigo']."</td>"; echo "<td>".$fila['nombre']."</td>"; echo "<td>".$fila['horario']."</td>"; echo "<td>".$fila['fecha_inicio']."</td>"; echo "<td>".$fila['fecha_fin']."</td>"; echo "<td>".$fila['precio']."</td>"; echo "</tr>"; } ?> </table> <?php } ?> </body> </html> — estilos.css table, th, td{ border: 1px solid #000; } — academia_idiomas.sql 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.
Spoiler Inside | SelectShow> |
---|---|
— conexion.php <?php 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 <?php 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> <?php session_start(); if (isset($_SESSION['curso_insertado'])) { echo '<p>' . $_SESSION['curso_insertado'] . '</p>'; 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> <?php } 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> <?php while ($fila = mysqli_fetch_assoc($resultados)) { echo "<tr>"; echo "<td>" . $fila['codigo'] . "</td>"; echo "<td>" . $fila['nombre'] . "</td>"; echo "<td>" . $fila['horario'] . "</td>"; echo "<td>" . $fila['fecha_inicio'] . "</td>"; echo "<td>" . $fila['fecha_fin'] . "</td>"; echo "<td>" . $fila['precio'] . "</td>"; echo "</tr>"; } ?> </table> <?php } ?> </body> </html> — form-aniadir.php <!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> <?php session_start(); if(isset($_SESSION['curso_no_insertado'])){ echo '<p>'.$_SESSION['curso_no_insertado'].'</p>'; 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 <?php 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 table, th, td{ border: 1px solid #000; } label, input{ display: block; } — academia_idiomas.sql 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.
Spoiler Inside | SelectShow> |
---|---|
— index.php <?php 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> <?php session_start(); if (isset($_SESSION['curso_insertado'])) { echo '<p>' . $_SESSION['curso_insertado'] . '</p>'; 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> <?php } 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> <?php while ($fila = mysqli_fetch_assoc($resultados)) { echo "<tr>"; echo "<td>" . $fila['codigo'] . "</td>"; echo "<td>" . $fila['nombre'] . "</td>"; echo "<td>" . $fila['horario'] . "</td>"; echo "<td>" . $fila['fecha_inicio'] . "</td>"; echo "<td>" . $fila['fecha_fin'] . "</td>"; echo "<td>" . $fila['precio'] . "</td>"; echo "</tr>"; } ?> </table> <?php } ?> </body> </html> — conexion.php <?php 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 <!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> <?php session_start(); if(isset($_SESSION['curso_no_insertado'])){ echo '<p>'.$_SESSION['curso_no_insertado'].'</p>'; 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 <?php 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. <br/>'; } if($finicial > $ffin){ $errores .= '- La fecha inicial no puede ser mayor que la de fin. <br/>'; } if(is_numeric($precio)){ if($precio < 0){ $errores .= '- El precio debe ser positivo. <br/>'; } }else{ $errores .= '- El precio debe ser un número. <br/>'; } 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 table, th, td{ border: 1px solid #000; } label, input{ display: block; } — academia_idiomas.sql 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.
Spoiler Inside | SelectShow> |
---|---|
— index.php <?php 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> <?php session_start(); if (isset($_SESSION['curso_correcto'])) { echo '<p>' . $_SESSION['curso_correcto'] . '</p>'; 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> <?php } 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> <?php while ($fila = mysqli_fetch_assoc($resultados)) { echo "<tr>"; echo "<td>" . $fila['codigo'] . "</td>"; echo "<td>" . $fila['nombre'] . "</td>"; echo "<td>" . $fila['horario'] . "</td>"; echo "<td>" . $fila['fecha_inicio'] . "</td>"; echo "<td>" . $fila['fecha_fin'] . "</td>"; echo "<td>" . $fila['precio'] . "</td>"; echo "<td><a href='form-curso.php?idcurso=" . $fila['codigo'] . "'>Editar</a></td>"; echo "</tr>"; } ?> </table> <?php } ?> </body> </html> — conexion.php <?php 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 <!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> <?php session_start(); if (isset($_SESSION['curso_no_correcto'])) { echo '<p>' . $_SESSION['curso_no_correcto'] . '</p>'; 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> <?php 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="<?php if(isset($curso)){ echo $curso['codigo']; } ?>"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" required value="<?php 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="<?php if(isset($curso)){ echo $curso['horario']; } ?>"> <label for="finicial">Fecha inicial</label> <input type="date" name="finicial" id="finicial" required value="<?php if(isset($curso)){ echo $curso['fecha_inicial']; } ?>"> <label for="ffin">Fecha fin</label> <input type="date" name="ffin" id="ffin" required value="<?php if(isset($curso)){ echo $curso['fecha_fin']; } ?>"> <label for="precio">Precio</label> <input type="text" name="precio" id="precio" required value="<?php if(isset($curso)){ echo $curso['precio']; } ?>"> <input type="submit" name="enviar" value="Enviar"> </form> </body> </html> — registro-curso.php <?php 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. <br/>'; } if($finicial > $ffin){ $errores .= '- La fecha inicial no puede ser mayor que la de fin. <br/>'; } if(is_numeric($precio)){ if($precio < 0){ $errores .= '- El precio debe ser positivo. <br/>'; } }else{ $errores .= '- El precio debe ser un número. <br/>'; } 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 table, th, td{ border: 1px solid #000; } label, input{ display: block; } — academia_idiomas.sql 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.
Spoiler Inside | SelectShow> |
---|---|
— index.php <?php 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> <?php session_start(); if (isset($_SESSION['curso_correcto'])) { echo '<p>' . $_SESSION['curso_correcto'] . '</p>'; unset($_SESSION['curso_correcto']); } if (isset($_SESSION['cursos_borrados'])) { echo '<p>' . $_SESSION['cursos_borrados'] . '</p>'; unset($_SESSION['cursos_borrados']); } if (isset($_SESSION['cursos_no_borrados'])) { echo '<p>' . $_SESSION['cursos_no_borrados'] . '</p>'; 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> <?php } 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> <?php while ($fila = mysqli_fetch_assoc($resultados)) { echo "<tr>"; echo "<td><input type='checkbox' name='selec_curso[]' value='".$fila['codigo']."' /></td>"; echo "<td>" . $fila['codigo'] . "</td>"; echo "<td>" . $fila['nombre'] . "</td>"; echo "<td>" . $fila['horario'] . "</td>"; echo "<td>" . $fila['fecha_inicio'] . "</td>"; echo "<td>" . $fila['fecha_fin'] . "</td>"; echo "<td>" . $fila['precio'] . "</td>"; echo "<td><a href='form-curso.php?idcurso=" . $fila['codigo'] . "'>Editar</a></td>"; echo "<td><a href='borrar-cursos.php?idcurso=" . $fila['codigo'] . "'>Borrar</a></td>"; echo "</tr>"; } ?> </table> <input type="submit" value="Borrar cursos seleccionados" /> </form> <?php } ?> </body> </html> — form-curso.php <!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> <?php session_start(); if(isset($_SESSION['curso_no_correcto'])){ echo '<p>'.$_SESSION['curso_no_correcto'].'</p>'; 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><?php 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="<?php if(isset($curso)){ echo $curso['codigo']; } ?>"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" required value="<?php 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="<?php if(isset($curso)){ echo $curso['horario']; } ?>"> <label for="finicial">Fecha inicial</label> <input type="date" name="finicial" id="finicial" required value="<?php if(isset($curso)){ echo $curso['fecha_inicio']; } ?>"> <label for="ffin">Fecha fin</label> <input type="date" name="ffin" id="ffin" required value="<?php if(isset($curso)){ echo $curso['fecha_fin']; } ?>"> <label for="precio">Precio</label> <input type="text" name="precio" id="precio" required value="<?php if(isset($curso)){ echo $curso['precio']; } ?>"> <input type="submit" name="enviar" value="Enviar"> </form> </body> </html> — registro-curso.php <?php 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. <br/>'; } if($finicial > $ffin){ $errores .= '- La fecha inicial no puede ser mayor que la de fin. <br/>'; } if(is_numeric($precio)){ if($precio < 0){ $errores .= '- El precio debe ser positivo. <br/>'; } }else{ $errores .= '- El precio debe ser un número. <br/>'; } 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 table, th, td{ border: 1px solid #000; } label, input{ display: block; } — borrar-curso.php <?php 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 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.
Spoiler Inside | SelectShow> |
---|---|
–index.php <?php 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> <?php session_start(); if (isset($_SESSION['curso_correcto'])) { echo '<p>' . $_SESSION['curso_correcto'] . '</p>'; unset($_SESSION['curso_correcto']); } if (isset($_SESSION['cursos_borrados'])) { echo '<p>' . $_SESSION['cursos_borrados'] . '</p>'; unset($_SESSION['cursos_borrados']); } if (isset($_SESSION['cursos_no_borrados'])) { echo '<p>' . $_SESSION['cursos_no_borrados'] . '</p>'; 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> <?php } 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> <?php while ($fila = mysqli_fetch_assoc($resultados)) { echo "<tr>"; echo "<td><input type='checkbox' name='selec_curso[]' value='" . $fila['codigo'] . "' /></td>"; echo "<td>" . $fila['codigo'] . "</td>"; echo "<td>" . $fila['nombre'] . "</td>"; echo "<td>" . $fila['horario'] . "</td>"; echo "<td>" . $fila['fecha_inicio'] . "</td>"; echo "<td>" . $fila['fecha_fin'] . "</td>"; echo "<td>" . $fila['precio'] . "</td>"; echo "<td><a href='form-curso.php?idcurso=" . $fila['codigo'] . "'>Editar</a></td>"; echo "<td><a href='borrar-cursos.php?idcurso=" . $fila['codigo'] . "'>Borrar</a></td>"; echo "</tr>"; } ?> </table> <input type="submit" value="Borrar cursos seleccionados" /> </form> <?php } ?> </body> </html> — conexion.php <?php 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 <!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> <?php session_start(); if(isset($_SESSION['curso_no_correcto'])){ echo '<p>'.$_SESSION['curso_no_correcto'].'</p>'; 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><?php 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="<?php if(isset($curso)){ echo $curso['codigo']; } ?>"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" required value="<?php 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="<?php if(isset($curso)){ echo $curso['horario']; } ?>"> <label for="finicial">Fecha inicial</label> <input type="date" name="finicial" id="finicial" required value="<?php if(isset($curso)){ echo $curso['fecha_inicio']; } ?>"> <label for="ffin">Fecha fin</label> <input type="date" name="ffin" id="ffin" required value="<?php if(isset($curso)){ echo $curso['fecha_fin']; } ?>"> <label for="precio">Precio</label> <input type="text" name="precio" id="precio" required value="<?php if(isset($curso)){ echo $curso['precio']; } ?>"> <input type="submit" name="enviar" value="Enviar"> </form> </body> </html> — registro-curso.php <?php 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. <br/>'; } if($finicial > $ffin){ $errores .= '- La fecha inicial no puede ser mayor que la de fin. <br/>'; } if(is_numeric($precio)){ if($precio < 0){ $errores .= '- El precio debe ser positivo. <br/>'; } }else{ $errores .= '- El precio debe ser un número. <br/>'; } 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 <?php 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 <!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> <?php 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"> <?php $sql = "select * from cursos"; require_once "conexion.php"; $resultado = mysqli_query($conexion, $sql); while($fila = mysqli_fetch_assoc($resultado)){ ?> <option value="<?php echo $fila['codigo'] ?>"><?php echo $fila['nombre'] ?></option> <?php } ?> </select> <input type="submit" value="Añadir" /> </form> </body> </html> — aniadir-alumno.php <?php 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 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.
Spoiler Inside | SelectShow> |
---|---|
— index.php <?php 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> <?php session_start(); if (isset($_SESSION['curso_correcto'])) { echo '<p>' . $_SESSION['curso_correcto'] . '</p>'; unset($_SESSION['curso_correcto']); } if (isset($_SESSION['cursos_borrados'])) { echo '<p>' . $_SESSION['cursos_borrados'] . '</p>'; unset($_SESSION['cursos_borrados']); } if (isset($_SESSION['cursos_no_borrados'])) { echo '<p>' . $_SESSION['cursos_no_borrados'] . '</p>'; 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> <?php } 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> <?php while ($fila = mysqli_fetch_assoc($resultados)) { echo "<tr>"; echo "<td><input type='checkbox' name='selec_curso[]' value='" . $fila['codigo'] . "' /></td>"; echo "<td>" . $fila['codigo'] . "</td>"; echo "<td>" . $fila['nombre'] . "</td>"; echo "<td>" . $fila['horario'] . "</td>"; echo "<td>" . $fila['fecha_inicio'] . "</td>"; echo "<td>" . $fila['fecha_fin'] . "</td>"; echo "<td>" . $fila['precio'] . "</td>"; echo "<td><a href='form-curso.php?idcurso=" . $fila['codigo'] . "'>Editar</a></td>"; echo "<td><a href='borrar-cursos.php?idcurso=" . $fila['codigo'] . "'>Borrar</a></td>"; echo "<td><a href='listar-alumnos.php?idcurso=" . $fila['codigo'] . "'>Listar alumnos</a></td>"; echo "</tr>"; } ?> </table> <input type="submit" value="Borrar cursos seleccionados" /> </form> <?php } ?> </body> </html> — conexion.php <?php 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 <!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> <?php session_start(); if(isset($_SESSION['curso_no_correcto'])){ echo '<p>'.$_SESSION['curso_no_correcto'].'</p>'; 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><?php 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="<?php if(isset($curso)){ echo $curso['codigo']; } ?>"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" required value="<?php 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="<?php if(isset($curso)){ echo $curso['horario']; } ?>"> <label for="finicial">Fecha inicial</label> <input type="date" name="finicial" id="finicial" required value="<?php if(isset($curso)){ echo $curso['fecha_inicio']; } ?>"> <label for="ffin">Fecha fin</label> <input type="date" name="ffin" id="ffin" required value="<?php if(isset($curso)){ echo $curso['fecha_fin']; } ?>"> <label for="precio">Precio</label> <input type="text" name="precio" id="precio" required value="<?php if(isset($curso)){ echo $curso['precio']; } ?>"> <input type="submit" name="enviar" value="Enviar"> </form> </body> </html> — registro-curso.php <?php 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. <br/>'; } if($finicial > $ffin){ $errores .= '- La fecha inicial no puede ser mayor que la de fin. <br/>'; } if(is_numeric($precio)){ if($precio < 0){ $errores .= '- El precio debe ser positivo. <br/>'; } }else{ $errores .= '- El precio debe ser un número. <br/>'; } 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 <?php 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 <!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> <?php 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"> <?php $sql = "select * from cursos"; require_once "conexion.php"; $resultado = mysqli_query($conexion, $sql); while($fila = mysqli_fetch_assoc($resultado)){ ?> <option value="<?php echo $fila['codigo'] ?>"><?php echo $fila['nombre'] ?></option> <?php } ?> </select> <input type="submit" value="Añadir" /> </form> </body> </html> — aniadir-alumno.php <?php 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 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
Spoiler Inside | SelectShow> |
---|---|
— index.php <!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> <?php require "conexion.php"; $sql = "SELECT * FROM pokemon"; $resultados = $conexion->query($sql); $resultados->execute(); while($fila = $resultados->fetch(PDO::FETCH_OBJ)){ echo $fila->nombre."<br/>"; } ?> </body> </html> — conexion.php <?php $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(). "<br/>"; exit; } ?> |
Espero que os sea de ayuda. Si tenéis dudas, preguntad. Estamos para ayudarte.
Deja una respuesta