sábado, 28 de marzo de 2015

PHP - Crear un sitio Web para gestionar becarios



Se trata de insertar en la tabla aquellos becarios que están en proceso de formación. Estos becarios tienen nombre, apellidos, una nacionalidad, un tipo de formación y un formador en una sala entre dos fechas determinadas.

Esta página tiene un código JavaScript que activa el área de formadores y las fechas, según el tipo de formación que seleccione.


También puede eliminar los datos de un becario:


Puede modificar todos los becarios al mismo tiempo:


Esta página contiene un JavaScript que activa las áreas de formadores y las fechas, según el tipo de formación que seleccione.

El esquema de la base de datos es:


Solución

Cree la base de datos formación.

Ejecute el script para crear unas tablas con sus correspondientes datos:

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
-- Estructura de la tabla `formador`
DROP TABLE IF EXISTS formador;
CREETE TABLE formador (
Id_formador int(11) NOT NULL AUTO_INCREMENT,
Apellido varchar(20) NOT NULL,
Nombre varchar(20) NOT NULL,
Id_sala int(11) NOT NULL,
PRIMARY KEY (Id_formador)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
-- Contenido de la tabla `formador`
INSERT INTO formador (Id_formador, Apellido, Nombre, Id_sala)
VALUES
(1, ’Morales HonHon’, ’Estefanía’, 1),
(2, ’García Arripe’, ’Pablo’, 2),
(3, ’Mártin Cruz’, ’Emilio’, 3),
(4, ’Gonzalez Sánchez’, ’María’, 4);
-- Estructura de la tabla `nacionalidad`
DROP TABLE IF EXISTS nacionalidad;
CREATE TABLE nacionalidad (
Id_nacionalidad int(11) NOT NULL AUTO_INCREMENT,
Etiqueta varchar(25) NOT NULL,
PRIMARY KEY (Id_nacionalidad)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
-- Contenido de la tabla `nacionalidad`
INSERT INTO nacionalidad (Id_nacionalidad, Etiqueta) VALUES
(1, ’Francés’),
(2, ’Inglés’),
(3, ’Alemán’),
(4, ’Ruso’);
-- Estructura de la tabla `sala`
DROP TABLE IF EXISTS sala;
CREATE TABLE sala (
Id_sala int(11) NOT NULL AUTO_INCREMENT,
Etiqueta varchar(20) NOT NULL,
PRIMARY KEY (Id_sala)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
-- Contenido de la tabla `sala`
INSERT INTO sala (Id_sala, Etiqueta) VALUES
(1, ’101’),
(2, ’102’),
(3, ’201’),
(4, ’202’);
-- Estructura de la tabla `becario`
DROP TABLE IF EXISTS becario;
CREATE TABLE becario (
Id int(11) NOT NULL AUTO_INCREMENT,
Nombre varchar(20) NOT NULL,
Apellido varchar(20) NOT NULL,
Id_nacionalidad int(11) NOT NULL,
Id__tipo_formacion int(11) NOT NULL,
PRIMARY KEY (Id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
-- Contenido de la tabla `becario`
INSERT INTO becario (Id, Apellido, Nombre, Id_nacionalidad,
Id__tipo_formacion) VALUES
(1, ’López’, ’Nadia’, 4, 1),
(2, ’Del Pozo’, ’Carolina’, 1, 2),
(8, ’Gómez’, ’Alez’, 2, 1),
(4, ’Rodríguez’, ’María’, 3, 2),
(6, ’Morales’, ’Estefanía’, 1, 2);
-- Estructura de la tabla `becario_formador`
DROP TABLE IF EXISTS becario_formador;
CREATE TABLE becario_formador (
Id_becario int(11) NOT NULL,
Id_formador int(11) NOT NULL,
Fecha_inicio Date NOT NULL,
Fecha_fin Date NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- Contenido de la tabla `becario_formador`
INSERT INTO becario_formador (Id_becario, Id_formador,
Fecha_inicio, Fecha_fin) VALUES
(1, 1, ’2013-07-25’, ’2013-10-28’),
(1, 2, ’2013-10-31’, ’2013-12-30’),
(2, 4, ’2013-08-26’, ’2013-10-18’),
(8, 2, ’2013-08-15’, ’2014-02-15’),
(6, 4, ’2013-08-21’, ’2013-10-21’),
(4, 3, ’2013-08-17’, ’2014-02-21’);
-- Estructura de la tabla `_tipo_formacion`
DROP TABLE IF EXISTS _tipo_formacion;
CREATE TABLE _tipo_formacion (
Id__tipo_formacion int(11) NOT NULL AUTO_INCREMENT,
Etiqueta varchar(25) NOT NULL,
PRIMARY KEY (Id__tipo_formacion)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
-- Contenido de la tabla `_tipo_formacion`
INSERT INTO _tipo_formacion (Id__tipo_formacion, Etiqueta) VALUES
(1, ’Web designer’),
(2, ’Desarrollador’);
-- Estructura de la tabla `_tipo_formacion_formador`
DROP TABLE IF EXISTS _tipo_formacion_formador;
CREATE TABLE _tipo_formacion_formador (
Id__tipo_formacion int(11) NOT NULL,
Id_formador int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- Contenido de la tabla `_tipo_formacion_formador`
INSERT INTO _tipo_formacion_formador (Id__tipo_formacion,
Id_formador) VALUES
(1, 1),
(1, 2),
(2, 3),
(2, 4);
  • La página formacion.php es:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<?php
$connect = mysqli_connect("127.0.0.1", "root", "", "formacion");
/* Comprobar la conexión */
if (!$connect) {
echo "Fallo de la conexión : ".mysqli_connect_error();
exit();
}
setlocale (LC_TIME, ’es-ES.utf-8’,’esp’);
?>
<head>
<title>Ejercicio formación</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-15" />
<script language="JavaScript">
function comprueba_date(fecha_recibida) {
if (fecha_recibida == ’’) {
alert(’fecha no válida’);
document.formulario.enviar.disabled=true;
}
else {
document.formulario.enviar.disabled=false;
}
}
function enable_formador() {
var tabla_formacion = new Array();
<?php
$consulta = "SELECT * FROM _tipo_formacion_formador ORDER BY
Id__tipo_formacion";
if ($resultado = mysqli_query($connect,$consulta)) {
$incremento = 0;
$Id__tipo_formacion = 0;
/* busca la matriz asociativa */
while ($registro = mysqli_busca_assoc($resultado)) {
//creación dinámica de una tabla JavaScript de dos dimensiones
//que contiene el Id_formacion en la primera dimensión,
//un contador en la segunda dimensión y el Id_formador como valor.
if ($Id__tipo_formacion == $registro[’Id__tipo_formacion’]) {
echo "matriz_formacion[".$registro[’Id__tipo_formacion’]."]
[".$increment."]=".$registro[’Id_formador’].";\n";
}
else {
$Id__tipo_formacion = $registro[’Id__tipo_formacion’];
$incremento = 0;
echo "matriz_formacion[".$registro[’Id__tipo_formacion’]."]
= new Array();\n";
echo "matriz_formacion[".$registro[’Id__tipo_formacion’]."]
[".$increment."]=".$registro[’Id_formador’].";\n";
}
$incremento = $incremento + 1;
}
/*libera el objeto resultado */
mysqli_free_result($resultado);
}
?>
//reajustar los checkbox
var i;
var obj_input;
for (i = 0; i < document.formulario.elementos.length; i++)
{
obj_input = document.formulario.elementos[i];
if(obj_input.type=="checkbox") // comprueba si CheckBox
{
obj_input.disabled=true;
obj_input.checked=false;
}
if(obj_input.name.substring(0,5)=="inicio" ||
obj_input.name.substring(0,3)=="fin") // comprueba si fecha inicio o
// si fecha de fin
{
obj_input.disabled=true;
}
}
// recuperar el Id_formacion seleccionado en
//la lista _tipo_formacion
id_formacion=document.formulario._tipo_formacion.options[
document.formulario._tipo_formacion.selectedIndex].value;
var matriz_formador = new Array();
matriz_formador = matriz_formacion[id_formacion];
for(var i= 0; i < matriz_formador.length; i++)
{
document.getElementById(
"formador"+matriz_formador[i]).disabled=false;
document.getElementById(
"inicio"+matriz_formador[i]).disabled=false;
document.getElementById(
"fin"+matriz_formador[i]).disabled=false;
}
}
</script>
</head>
<body onload="enable_formador()">
<h2>Insertar un becario en formación</h2><br />
<form name="formulario" id="formulario"
action="añadir_becario.php" method="POST">
nom: <input type="text" name="apellido"><br />
nombre: <input type="text" name="nombre"><br />
nacionalidad: <select name="nacionalidad">
<?php
$consulta = "SELECT * FROM nacionalidad";
if ($resultado = mysqli_query($connect,$consulta)) {
/* busca la matriz asociativa */
while ($registro = mysqli_busca_assoc($resultado)) {
echo "<option value=’".$registro[’Id_nacionalidad’]."’>";
echo $registro[’Etiqueta’]."</option>";
}
/*libera el objeto resultado */
mysqli_free_result($resultado);
}
?>
</select><br /><br />
tipo de formación: <select name="_tipo_formacion"
onchange="enable_formador()">
<?php
$consulta = "SELECT * FROM _tipo_formacion";
if ($resultado = mysqli_query($connect,$consulta)) {
/* busca la matriz asociativa */
while ($registro = mysqli_busca_assoc($resultado)) {
echo "<option value=’".$registro[’Id__tipo_formacion’]."’>";
echo $registro[’Etiqueta’]."</option>";
}
/*libera el objeto resultado */
mysqli_free_result($resultado);
}
?>
</select><br /><br />
formadores por fecha:<br />
<?php
$consulta = "SELECT * FROM formador left join sala on
formador.id_sala = sala.id_sala";
if ($resultado = mysqli_query($connect,$consulta)) {
/* busca la matriz asociativa */
while ($registro = mysqli_busca_assoc($resultado)) {
echo "<input type=’checkbox’";
echo "value=’".$registro[’Id_formador’];
echo "’id=’formador".$registro[’Id_formador’];
echo "’name=’formador[]’>".$registro[’Nombre’]." ".$registro[’Apellido’];
echo " en la sala ".$registro[’Etiqueta’].",";
echo " inicio : <input type=’text’";
echo "’name=’inicio".$registro[’Id_formador’];
echo "’id=’inicio".$registro[’Id_formador’];
echo "’value=’".strftime("%d/%m/%Y");
echo "onchange=’comprueba_Fecha(this.value)’ />,";
echo " fin: <input tipo=’text’";
echo "’name=’fin".$registro[’Id_formador’];
echo "’id=’fin".$registro[’Id_formador’]."’ value=’".date(’d/m/Y’,
strtotime(’+6 month’))."’ onchange=’comprueba_date(this.value)’ /><br />;
}
/* libera el objeto resultado */
mysqli_free_result($resultado);
}
?>
<br />
<input type="submit" name="enviar" value="Enviar" />
</form>
<br />
<a href="lista_becario_que_eliminar.php">Eliminar un
becario</a> <a href="lista_becario_que_modificar.php">Modificar
un becario</a>
<?php
/* Cierre de la conexión */
mysqli_close($connect);
?>
</body>
</html>

  • La página añadir_becario.php inserta el becario en la base de datos:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<?php
$connect = mysqli_connect("127.0.0.1", "root", "", "formacion");
/* Comprobar la conexión */
if (!$connect) {
echo "Fallo de la conexión : ".mysqli_connect_error();
exit();
}
?>
<head>
<title>Ejercicio formación</title>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-15" />
</head>
<body>
<h2>Recepción de datos del becario que se va a insertar</h2>
apellido: <?php echo $_POST[’apellido’];?><br />
nombre: <?php echo $_POST[’nombre’];?><br />
nacionalidad: <?php echo $_POST[’nacionalidad’];?><br />
tipo de formación: <?php echo $_POST[’_tipo_formacion’];?><br />
<?php
$consulta = "INSERT INTO becario (Apellido, Nombre, Id_nacionalidad,
Id__tipo_formacion) VALUES (’".htmlentities(addslashes(
$_POST[’apellido’]), ENT_QUOTES)."’,’".htmlentities(addslashes
($_POST[’nombre’]),
ENT_QUOTES)."’,".$_POST[’nacionalidad’].
",".$_POST[’_tipo_formacion’].")";
$resultado = mysqli_query($connect,$consulta);
$inicio de sesión=mysqli_insert_id($connect);
if (isset($_POST[’formador’])) {?>
<br />
<?php //define la zona de España para la fecha
date_default_timezone_set(’Europe/Paris’);
foreach ($_POST[’formador’] as $valor) {
$dt_inicio = date_create_from_format(’d/m/Y’, $_POST[’inicio’.$valor]);
$dt_fin = date_create_from_format(’d/m/Y’, $_POST[’fin’.$valor]);
$consulta = "INSERT INTO becario_formador (Id_becario, Id_formador,
Fecha_inicio, Fecha_fin) VALUES (".$inicio de sesión.",".
$valor.",’".$dt_inicio->format(’Y/m/d’)."’,’".$dt_fin->formato(
’Y/m/d’)."’)";
$resultado = mysqli_query($connect,$consulta);
}
}
/* Cierre de la conexión */
mysqli_close($connect);
?>
<br />
¡El becario se ha agregado con éxito!
<br />
<a href="formacion.php">Regreso a agregar becario</a>
</body>
</html>
  • La página lista_becario_a_eliminar.php es:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<?php
$connect = mysqli_connect("127.0.0.1", "root", "", ”formacion”);
/* Comprobar la conexión */
if (!$connect) {
echo "Fallo de la conexión : ".mysqli_connect_error();
exit();
}
?>
<head>
<title>Ejercicio formación</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" />
</head>
<body>
<h2>Eliminar los datos del becario</h2><br />
<form action="eliminar_becario.php" method="POST">
<tabla border="1">
<tr>
<th width="100px">Apellido</th> <th width="100px">Nombre</th> <th
width="100px">Nacionalidad</th> <th width="100px">Tipo de
formación</th> <th width="300px">Formador - Sala - Fecha inicio -
Fecha fin</th><th width="50px">Eliminación</th>
</tr>
<?php
$consulta = "SELECT *,nacionalidad.Etiquetas
Lib_nacionalidad,_tipo_formacion.Etiqueta as Lib__tipo_formacion,
becario.Id as Id_becario FROM (becario".
" INNER JOIN nacionalidad ON becario.Id_nacionalidad =
nacionalidad.Id_nacionalidad)".
" INNER JOIN _tipo_formacion ON becario.Id__tipo_formacion =
_tipo_formacion.Id__tipo_formacion".
" ORDER BY Nombre";
if ($resultado = mysqli_query($connect,$consulta)) {
Fecha_default_timezone_set(’Europe/Paris’);
/* busca la matriz asociativa */
while ($registro = mysqli_busca_assoc($resultado)) {
echo "<tr>";
echo "<td>".$registro[’Apellido’]."</td>";
echo "<td>".$registro[’Nombre’]."</td>";
echo "<td>".$registro[’Nacionalidad’]."</td>";
echo "<td>".$registro[’Tipo_formacion’]."</td>";
echo "<td>";
$consulta_formador = "SELECT * FROM becario_formador INNER JOIN
formador ON becario_formador.Id_formador = formador.Id_
formador INNER JOIN sala ON formador.Id_sala = sala.Id_sala WHERE
becario_formador.Id_becario = ".$registro[’Id’];
if ($resultado_formador =
mysqli_query($connect,$consulta_formador)) {
/* busca la matriz asociativa */
while ($registro_formador =
mysqli_busca_assoc($resultado_formador)) {
$dt_inicio = date_create_from_format(’Y-m-d’,
$registro_formador[’Fecha_inicio’]);
echo $registro_formador[’Nombre’]." - ".$registro_formador[
’Etiqueta’]." - ".$dt_inicio->format(’d/m/Y’)." -
".$registro_formador[’Fecha_fin’]."<br />";
}
}
echo "&nbsp;</td>";
echo "<td><input type=’checkbox’ name=’supresión[]’
value=’".$registro[’Id_becario’]."’ /></td>";
echo "</tr>";
}
}
/* Cierre de la conexión */
mysqli_close($connect);
?>
</tabla>
<br />
<input type="submit" name="eliminar" value="eliminar" />
</form>
<br />
<a href="formacion.php">Añadir un becario</a> <a
href="lista_becario_que_modificar.php">Modificar un becario</a>
</body>
</html>
  • La página eliminar_becario.php elimina en la base de datos:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<?php
$connect = mysqli_connect("127.0.0.1", "root", "", ”formacion”);
/* Comprobar la conexión */
if (!$connect) {
echo "Fallo de la conexión : ".mysqli_connect_error();
exit();
}
?>
<head>
<title>Ejercicio formación</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" />
</head>
<body>
<?php
if (isset($_POST[’eliminar’])) {
foreach ($_POST[’eliminar’] as $valor) {
$consulta = "DELETE FROM becario_formador WHERE Id_becario =
".$valor;
$resultado = mysqli_query($connect,$consulta);
$consulta = "DELETE FROM becario WHERE Id = ".$valor;
$resultado = mysqli_query($connect,$consulta);
}
}
/* Cierre de la conexión */
mysqli_close($connect);
header(’location:lista_becario_que_eliminar.php’);
?>
</body>
</html>
  • La página lista_becario_que_modificar.php es:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<?php
$connect = mysqli_connect("127.0.0.1", "root", "", ”formacion”);
/* Comprobar la conexión */
if (!$connect) {
echo "Fallo de la conexión : ".mysqli_connect_error();
exit();
}
?>
<head>
<title>Ejercicio formación</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" />
<script language="JavaScript">
function comprueba_Fecha(Fecha_recibida) {
if (Fecha_recibida == ’’) {
alert(’Fecha no válida’);
document.formulario.enviar.disabled=true;
}
else {
document.formulario.enviar.disabled=false;
}
}
function enable_formador(param) { //Id_becario en parámetro
//reajustar a cero los checkbox
var i;
var obj_input;
for (i = 0; i < document.formulario.elements.length; i++)
{
obj_input = document.formulario.elements[i];
if(obj_input.type=="checkbox" &&
obj_input.name.substring(0,12)!="modificacion") // prueba si
//el tipo = CheckBox y el nombre <> modificacion
{
obj_input.disabled=true;
if (obj_input.id.substring(obj_input.id.indexOf("_")+1) ==
param) { //elimina la selección de los checkbox si modifica la del
//tipo de formación
obj_input.checked=false;
}
}
if(obj_input.name.substring(0,5)=="inicio" ||
obj_input.name.substring(0,3)=="fin") // se prueba si fecha inicio
// o fecha fin
{
obj_input.disabled=true;
}
}
var matriz_formacion = new Array();
<?php
$consulta_stag = "SELECT *, becario.Id AS Id_becario FROM
becario".
" ORDER BY Nombre";
if ($resultado_stag = mysqli_query($connect,$consulta_stag)) {
while ($registro_stag = mysqli_busca_assoc($resultado_stag)) {
$consulta = "SELECT * FROM _tipo_formacion_formador ORDER
BY Id__tipo_formacion";
if ($resultado = mysqli_query($connect,$consulta)) {
$incremento = 0;
$Id__tipo_formacion = 0;
/* busca la matriz asociativa */
while ($registro = mysqli_busca_assoc($resultado)) {
if ($Id__tipo_formacion == $registro[’Id__tipo_formacion’]) {
echo "matriz_formacion[".
$registro[’Id__tipo_formacion’]."][".$increment."]=".
$registro[’Id_formador’].";\n";
}
else {
$Id__tipo_formacion = $registro[’Id__tipo_formacion’];
$incremento = 0;
echo "matriz_formacion[".
$registro[’Id__tipo_formacion’]."] = new Array();\n";
echo "matriz_formacion[".
$registro[’Id__tipo_formacion’]."][".$increment."]=".
$registro[’Id_formador’].";\n";
}
$incremento = $incremento + 1;
}
/*libera el objeto resultado */
mysqli_free_result($resultado);
}
?>
id_formacion=document.formulario._tipo_formacion<?php echo
$registro_stag[’Id_becario’];?>.options[document.formulario.tipo_
formacion<?php echo
$registro_stag[’Id_becario’];?>.selectedIndex].value;
var matriz_formador = new Array();
matriz_formador = matriz_formacion[id_formacion];
for(var i= 0; i < matriz_formador.length; i++)
{
document.getElementById("formador"+matriz_formador[i]+"_<?php
echo $registro_stag[’Id_becario’];?>").disabled=false;
document.getElementById("inicio"+matriz_formador[i]+"_<?php
echo $registro_stag[’Id_becario’];?>").disabled=false;
document.getElementById("fin"+matriz_formador[i]+"_<?php
echo $registro_stag[’Id_becario’];?>").disabled=false;
}
<?php }//fin while
}//fin si ?>
}
</script>
</head>
<body onload="enable_formador(0)">
<h2>Modificación de los datos del becario</h2><br />
<form name="formulario" id="formulario"
action="modificacion_becario.php" method="POST">
<tabla border="1">
<tr>
<th width="100px">Apellido</th> <th width="100px">Nombre</th>
<th width="100px">Nacionalidad</th> <th width="100px">Tipo de
formación</th> <th width="300px">Formador - Sala - Fecha inicio -
Fecha fin</th><th width="50px">Modificación</th>
</tr>
<?php
$consulta = "SELECT *, becario.Id AS Id_becario FROM becario".
" ORDER BY Nombre";
if ($resultado = mysqli_query($connect,$consulta)) {
date_default_timezone_set(’Europe/Paris’);
/* busca la matriz asociativa */
while ($registro = mysqli_busca_assoc($resultado)) {
echo "<tr>";
echo "<td><input type=’text’ name=’apellido".
$registro[’Id_becario’]."’ value=’".$registro[’Apellido’]."’ />
</td>";
echo "<td><input type=’text’ name=’nombre".
$registro[’Id_becario’]."’ value=’".$registro[’Nombre’]."’ /></td>";
echo "<td>";
echo ’<select name="nacionalidad’.
$registro[’Id_becario’].’">’;
$consulta_nac = "SELECT * FROM nacionalidad";
if ($resultado_nac = mysqli_query($connect,$consulta_nat)) {
/* busca la matriz asociativa */
while ($registro_nac = mysqli_busca_assoc($resultado_nat)) {
if ($registro_nac[’Id_nacionalidad’] == $registro[’Id_nacionalidad’]) {
echo "<option value=’".$registro_nac[’Id_nacionalidad’]."
’ selected=’selected’ >".$registro_nac[’Etiqueta’]."</option>";
}
else {
echo "<option value=’".$registro_nac[’Id_nacionalidad’].
"’>".$registro_nac[’Etiqueta’]."</option>";
}
}
/* libera el objeto resultado */
mysqli_free_result($resultado_nat);
}
echo "</select>";
echo "</td>";
echo "<td>";
echo ’<select name="_tipo_formacion’.$registro[’Id_becario’].’"
onchange="enable_formador(’.$registro[’Id_becario’].’)">’;
$consulta_form = "SELECT * FROM _tipo_formacion";
if ($resultado_form = mysqli_query($connect,$consulta_form)) {
/* busca la matriz asociativa */
while ($registro_form = mysqli_busca_assoc($resultado_form)) {
if ($registro_form[’Id__tipo_formacion’] ==
$registro[’Id__tipo_formacion’]) {
echo "<option value=’".$registro_form
[’Id__tipo_formacion’]."’ selected=’selected’>".$registro_form
[’Etiqueta’]."</option>";
}
else {
echo "<option value=’".$registro_form
[’Id__tipo_formacion’]."’>".$registro_form[’Etiqueta’]."</option>";
}
}
/*libera el objeto resultado */
mysqli_free_result($resultado_form);
}
echo "</select>";
echo "</td>";
echo "<td>";
$consulta_todo_formador = "SELECT * FROM formador left join
sala on formador.id_sala = sala.id_sala";
if ($resultado_todo_formador =
mysqli_query($connect,$consulta_todo_formador)) {
/* busca la matriz asociativa */
while ($registro_todo_formador = mysqli_busca_assoc($resultado_todo_formador)) {
$checked="";
$dt_inicio = date_create_from_format(’Y-m-d’,
strftime("%Y-%m-%d"));
$dt_fin = date_create_from_format(’Y-m-d’,strftime("%Y-
%m-%d",strtotime(’+6 month’)));
$consulta_formador = "SELECT * FROM becario_formador
INNER JOIN formador ON becario_formador.Id_formador =
formador.Id_formador INNER JOIN sala ON formador.Id_sala =
sala.Id_sala WHERE becario_formador.Id_becario =
".$registro[’Id’];
if ($resultado_formador =
mysqli_query($connect,$consulta_formador)) {
/* busca la matriz asociativa */
while ($registro_formador =
mysqli_busca_assoc($resultado_formador)) {
if ($registro_formador[’Id_formador’] ==
$registro_todo_formador[’Id_formador’]) {
$dt_inicio = date_create_from_format(’Y-m-d’,
$registro_formador[’Fecha_inicio’]);
$dt_fin = date_create_from_format(’Y-m-d’,
$registro_formador[’Fecha_fin’]);
$checked = "checked=’checked’";
}
}
}
echo "<input tipo=’checkbox’ ".$checked." id=’
formador".$registro_todo_formador[’Id_formador’]."_".
$registro[’Id_becario’]."’ name=’formador".$registro[’Id_becario’].
"[]’ value=’".$registro_todo_formador[’Id_formador’]."’ />";
echo $registro_todo_formador[’Nombre’]." - ".
$registro_todo_formador[’Etiqueta’]." - <input tipo=’text’ size=’8’
name=’inicio".$registro_todo_formador[’Id_formador’]."_".
$registro[’Id_becario’]."’ id=’inicio".$registro_todo_formador
[’Id_formador’]."_".$registro[’Id_becario’]."’ value=’"
.$dt_inicio->format(’d/m/Y’)."’ onchange=’comprueba_date(this.value)’ />";
echo "<input type=’text’ size=’8’ name=’fin".
$registro_todo_formador[’Id_formador’]."_".$registro[’Id_becario’]."’
id=’fin".$registro_todo_formador[’Id_formador’]."_"
.$registro[’Id_becario’]."’ value=’".$dt_fin->format(’d/m/Y’).
"’ onchange=’comprueba_date(this.value)’ /><br />";
}
/*libera el objeto resultado */
mysqli_free_result($resultado_todo_formador);
}
echo "&nbsp;</td>";
echo "<td><input type=’checkbox’ name=’modificacion[]’
value=’".$registro[’Id_becario’]."’ /></td>";
echo "</tr>";
}
}
/* Cierre de la conexión */
mysqli_close($connect);
?>
</tabla>
<br />
<input type="submit" name="modificar" value="modificar" />
</form>
<br />
<a href="formacion.php">Añadir un becario</a> <a
href="lista_becario_que_eliminar.php">Eliminar un becario</a>
</body>
</html>
  • La página modificación_becario.php cambia el becario en la base de datos:

<!DOCTYpe html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<?php
$connect = mysqli_connect("127.0.0.1", "root", "", "formacion");
/* Comprobar la conexión */
if (!$connect) {
echo "Fallo de la conexión : ".mysqli_connect_error();
exit();
}
?>
<head>
<title>Ejercicio formación</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-15" />
</head>
<body>
<?php
if (isset($_POST[’modificacion’])) {
date_default_timezone_set(’Europe/Paris’);
foreach ($_POST[’modificación’] as $valor) {
//Para modificar la tabla becario_formador, hay que
//eliminar y crear los que están controlados
$consulta = "DELETE FROM becario_formador WHERE Id_becario
= ".$valor;
$resultado = mysqli_query($connect,$consulta);
if (isset($_POST[’formador’.$valor])) {
foreach ($_POST[’formador’.$valor] as $valor_formador) {
$dt_inicio = date_create_from_format(’d/m/Y’,
$_POST[’inicio’.$valor_formador."_".$valor]);
$dt_fin = date_create_from_format(’d/m/Y’,
$_POST[’fin’.$valor_formador."_".$valor]);
$consulta_formador = "INSERT INTO becario_formador
(Id_becario, Id_formador, Fecha_inicio, Fecha_fin) VALUES
(".$valor.",".$valor_formador.",’".$dt_inicio->format(’Y/m/d’)."’,
’".$dt_fin->format(’Y/m/d’)."’)";
$resultado_formador =
mysqli_query($connect,$consulta_formador);
}
}
$consulta_becario = "UPDATE becario SET
Apellido=’".htmlentities(addslashes($_POST[’apellido’.$valor]),
ENT_QUOTES)."’
,Nombre=’".htmlentities(addslashes($_POST[’nombre’.$valor]),
ENT_QUOTES)."’,Id_nacionalidad=".$_POST[’nacionalidad’.$valor].",
Id__tipo_formacion=".$_POST[’_tipo_formacion’.$valor]." WHERE Id =
".$valor;
$resultado_becario =
mysqli_query($connect,$consulta_becario);
}
}
/* Cierre de la conexión */
mysqli_close($connect);
header(’location:lista_becario_que_modificar.php’);
?>
</body>
</html>


Espero haber ayudado en algo. Hasta la próxima oportunidad!






No hay comentarios:

Publicar un comentario

       
free counters

Páginas vistas en total según Google