Hola. Tengo un problema con un ejercicio.
La idea es hacer un formulario que recoja nombre,edad y poblacion.
Donde tendremos:
Se guardara en una BBDD "portal_web"
El script tiene que ser el siguiente (2 tablas) :
-usuarios -> nombre usuario, edad y id (clave primaria)
-poblacion -> nombre poblacion, id_usuario (que sera la id de la tabla anterior)
Importante: una poblacion puede ser la misma para mas de un usuario
despues lo guardare en un fichero "datos_usuario".
Os dejo los archivos
formulario.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Formulario</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 0.21" />
</head>
<body>
<!--Formulario-->
<form method="post" action="enviar.php">
<h1>Intriducir los datos:</h1>
Nombre: <input type="text" name="nombre" size="20"><br>
Edad: <input type="text" name="edad" size="20"><br>
Poblacion: <input type="text" name="poblacion" size="20"><br><br><br>
Reset<input name="reset" value="Borrar datos" type="reset">
Enviar datos<input name="submit" value="Enviar datos" type="submit">
</form>
</body>
</html>
enviar.php
<html>
<head>
</head>
<body>
<?php
$nombre=$_POST['nombre'];
$edad=$_POST['edad'];
$poblacion=$_POST['poblacion'];
print "Variable nombre: " . $_POST["nombre"] . "<br>";
print "Variable edad: " . $_POST["edad"] . "<br>";
print "Variable poblacion: " . $_POST["poblacion"] . "<br><br><br><br><br><br>";
?>
<?php
//recogemos llos datos del formulario
$nombre=$_POST['nombre'];
$edad=$_POST['edad'];
$poblacion=$_POST['poblacion'];
//conectamos a la BBDD
$conexion=mysql_connect("localhost", "root", "1234") or die ("No se ha podido establecer conexion");
//Seleccionamos la bbdd
mysql_select_db("portal_web",$conexion) or die("No se ha podido establecer conexion");
//comprobamos si ya existe el usuario
$existe = mysql_query ("SELECT usuarios.*, poblaciones.* FROM usuarios
INNER JOIN poblaciones ON (usuarios.id=poblaciones.id_usuario)");
if(mysql_num_rows($existe)==1){
echo "Ese usuario ya existe";
}else{
//Insertando en la base de datos
$sql="INSERT INTO 'usuarios' (nombre, edad) VALUES ('$nombre','$edad')";
mysql_query($sql,$conexion);
$ultimo_id = mysql_insert_id($conexion);;
$sql2="INSERT INTO 'poblaciones' (poblacion,id_usuario) VALUES ('$poblacion','$ultimo_id')";
mysql_query($sql2,$conexion) ;
mysql_close($conexion);
echo "muestras ".$ultimo_id." del usuario";
}
//lo grabamos en un fichero
$fecha=date("d m y");
$archivo= "datos_usuario.txt";
$fichero= "
Fecha: $fecha------
Nombre: $nombre------
Edad: $edad------
Poblacion: $poblacion
<br><br>";
$file= fopen($archivo,"a");
fputs($file, $fichero);
fclose($file);
echo "<br><br><br><br><br><br>";
echo '<a href="formulario.html"><b>Volver a la encuesta</b></a>';
?>
Gracias.Saludos