Foros del Web » Programando para Internet » PHP »

Formulario de registro en php

Estas en el tema de Formulario de registro en php en el foro de PHP en Foros del Web. Hola tengo un formulario creado por DW pero me gustaria hacerme el mio propio ya que creo que seria mas sencillo que entender el de ...
  #1 (permalink)  
Antiguo 14/02/2012, 12:56
 
Fecha de Ingreso: diciembre-2011
Mensajes: 151
Antigüedad: 12 años, 3 meses
Puntos: 1
Formulario de registro en php

Hola tengo un formulario creado por DW pero me gustaria hacerme el mio propio ya que creo que seria mas sencillo que entender el de DW...

Pongo el que tengo:

Código PHP:
Ver original
  1. <?php require_once('Connections/conexionzulo.php'); ?>
  2. <?php
  3. if (!function_exists("GetSQLValueString")) {
  4. function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
  5. {
  6.   if (PHP_VERSION < 6) {
  7.     $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  8.   }
  9.  
  10.   $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  11.  
  12.   switch ($theType) {
  13.     case "text":
  14.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  15.       break;    
  16.     case "long":
  17.     case "int":
  18.       $theValue = ($theValue != "") ? intval($theValue) : "NULL";
  19.       break;
  20.     case "double":
  21.       $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
  22.       break;
  23.     case "date":
  24.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  25.       break;
  26.     case "defined":
  27.       $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
  28.       break;
  29.   }
  30.   return $theValue;
  31. }
  32. }
  33.  
  34. // *** Redirect if email exists
  35. $MM_flag="MM_insert";
  36. if (isset($_POST[$MM_flag])) {
  37.   $MM_dupKeyRedirect="alta_emailrepetido.php";
  38.   $loginUsername = $_POST['strEmail'];
  39.   $LoginRS__query = sprintf("SELECT * FROM tblusuario WHERE strEmail=%s",  GetSQLValueString($loginUsername, "text"));
  40.   mysql_select_db($database_conexionzulo, $conexionzulo);
  41.   $LoginRS=mysql_query($LoginRS__query, $conexionzulo) or die(mysql_error());
  42.   $loginFoundUser = mysql_num_rows($LoginRS);
  43.  
  44.   //if there is a row in the database, the email was found - can not add the requested username
  45.   if($loginFoundUser){
  46.     $MM_qsChar = "?";
  47.     //append the email to the redirect page
  48.     if (substr_count($MM_dupKeyRedirect,"?") >=1) $MM_qsChar = "&";
  49.     $MM_dupKeyRedirect = $MM_dupKeyRedirect . $MM_qsChar ."requsername=".$loginUsername;
  50.     header ("Location: $MM_dupKeyRedirect");
  51.     exit;
  52.   }
  53. }
  54.  
  55. // *** Redirect if username exists
  56. $MM_flag="MM_insert";
  57. if (isset($_POST[$MM_flag])) {
  58.   $MM_dupKeyRedirect="alta_usuariorepetido.php";
  59.   $loginUsername = $_POST['strNombre'];
  60.   $LoginRS__query = sprintf("SELECT * FROM tblusuario WHERE strNombre=%s",  GetSQLValueString($loginUsername, "text"));
  61.   mysql_select_db($database_conexionzulo, $conexionzulo);
  62.   $LoginRS=mysql_query($LoginRS__query, $conexionzulo) or die(mysql_error());
  63.   $loginFoundUser = mysql_num_rows($LoginRS);
  64.  
  65.   //if there is a row in the database, the username was found - can not add the requested username
  66.   if($loginFoundUser){
  67.     $MM_qsChar = "?";
  68.     //append the username to the redirect page
  69.     if (substr_count($MM_dupKeyRedirect,"?") >=1) $MM_qsChar = "&";
  70.     $MM_dupKeyRedirect = $MM_dupKeyRedirect . $MM_qsChar ."requsername=".$loginUsername;
  71.     header ("Location: $MM_dupKeyRedirect");
  72.     exit;
  73.   }
  74. }
  75.  
  76.  
  77. $editFormAction = $_SERVER['PHP_SELF'];
  78. if (isset($_SERVER['QUERY_STRING'])) {
  79.   $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
  80. }
  81.  
  82. if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  83.   $insertSQL = sprintf("INSERT INTO tblusuario (strNombre, strEmail, intActivo, strPassword, strDireccion) VALUES (%s, %s, %s, %s, %s)",
  84.                        GetSQLValueString($_POST['strNombre'], "text"),
  85.                        GetSQLValueString($_POST['strEmail'], "text"),
  86.                        GetSQLValueString($_POST['intActivo'], "int"),
  87.                        GetSQLValueString($_POST['strPassword'], "text"),
  88.                        GetSQLValueString($_POST['strDireccion'], "text"));
  89.  
  90.   mysql_select_db($database_conexionzulo, $conexionzulo);
  91.   $Result1 = mysql_query($insertSQL, $conexionzulo) or die(mysql_error());
  92.  
  93.   $insertGoTo = "alta_ok.php";
  94.   if (isset($_SERVER['QUERY_STRING'])) {
  95.     $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
  96.     $insertGoTo .= $_SERVER['QUERY_STRING'];
  97.   }
  98.   header(sprintf("Location: %s", $insertGoTo));
  99. }
  100. ?>
  101. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  102. <html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/Principal.dwt.php" codeOutsideHTMLIsLocked="false" -->
  103. <head>
  104. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  105. <!-- InstanceBeginEditable name="doctitle" -->
  106. <title>El Zulo</title>
  107. <!-- InstanceEndEditable -->
  108. <!-- InstanceBeginEditable name="head" -->
  109. <script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>
  110. <link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" />
  111. <!-- InstanceEndEditable -->
  112. <link href="estilo/principal.css" rel="stylesheet" type="text/css" />
  113. </head>
  114.  
  115. <body>
  116.  
  117. <div class="container">
  118.    
  119. <div class="header"><div class="headerinterior"><img src="images/banner1.jpg" alt="Tienda Zulo" width="980" height="180" /></div>
  120. </div>
  121.   <div class="subcontenedor">
  122.   <div class="sidebar1">
  123.    <?php include("includes/catalogo.php"); ?> <!-- Incluimos el catalogo que llama a la base de datos -->
  124.   <!-- end .sidebar1 --></div>
  125.   <div class="content">
  126.     <h1><!-- InstanceBeginEditable name="Titulo" -->Alta Usuario<!-- InstanceEndEditable --></h1>
  127.     <!-- InstanceBeginEditable name="Contenido" -->
  128.     <p>Formulario de Alta:   </p>
  129.     <p>&nbsp;</p>
  130.     <form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">
  131.       <table align="center">
  132.         <tr valign="baseline">
  133.           <td nowrap="nowrap" align="right">Nombre:</td>
  134.           <td><span id="sprytextfield1">
  135.             <input type="text" name="strNombre" value="" size="32" />
  136.             <span class="textfieldRequiredMsg">Este campo es obligatorio.</span></span></td>
  137.         </tr>
  138.         <tr valign="baseline">
  139.           <td nowrap="nowrap" align="right">Email:</td>
  140.           <td><span id="sprytextfield2">
  141.           <input type="text" name="strEmail" value="" size="32" />
  142.           <span class="textfieldRequiredMsg">Este campo es obligatorio.</span><span class="textfieldInvalidFormatMsg">El Email no es correcto.</span></span></td>
  143.         </tr>
  144.  
  145.         <tr valign="baseline">
  146.           <td nowrap="nowrap" align="right">Contraseña:</td>
  147.           <td><span id="sprytextfield3">
  148.             <input type="password" name="strPassword" value="" size="32" />
  149.             <span class="textfieldRequiredMsg">Este campo es obligatorio.</span></span></td>
  150.         </tr>
  151.         <tr valign="baseline">
  152.           <td nowrap="nowrap" align="right">Direccion:</td>
  153.           <td><span id="sprytextfield4">
  154.             <input type="text" name="strDireccion" value="" size="32" />
  155.             <span class="textfieldRequiredMsg">Necesitamos la direccion para enviar el pedido.</span></span></td>
  156.         </tr>
  157.         <tr valign="baseline">
  158.           <td nowrap="nowrap" align="right">&nbsp;</td>
  159.           <td><input type="submit" value="Registrame!" /></td>
  160.         </tr>
  161.       </table>
  162.       <input type="hidden" name="intActivo" value="1" />
  163.       <input type="hidden" name="MM_insert" value="form1" />
  164.     </form>
  165.     <p>&nbsp;</p>
  166.     <script type="text/javascript">
  167. var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1");
  168. var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "email");
  169. var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3");
  170. var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4");
  171.     </script>
  172.     <!-- InstanceEndEditable --><!-- end .content --></div>
  173.     <!-- end .subcontenedor --></div>
  174.    
  175.   <div class="footer">
  176.     <p>Pie de Pagina.</p>
  177.     <!-- end .footer --></div>
  178.   <!-- end .container --></div>
  179. </body>
  180. <!-- InstanceEnd --></html>

Me gustaria algo asi... Que se requieran los campos, me gustaria tener 2 campos para contraseña y email para repetirlos y comprobar que coinciden... Y lo mas importante me gustaria que comprobase si el nombre o el mail existe ya en la base de datos.. Y redireccionarlo a alguna pagina de error (como lo tengo puesto yo) o avisarlo en el mismo formulario. La cosa es que no se por donde empezar...

El form action puede ser la misma pagina donde este el formulario, no ?
  #2 (permalink)  
Antiguo 14/02/2012, 13:23
Avatar de repara2  
Fecha de Ingreso: septiembre-2010
Ubicación: München
Mensajes: 2.445
Antigüedad: 13 años, 7 meses
Puntos: 331
Respuesta: Formulario de registro en php

https://www.google.com/search?client...w=1440&bih=706
__________________
Fere libenter homines, id quod volunt, credunt.
  #3 (permalink)  
Antiguo 14/02/2012, 13:26
Avatar de skiper0125  
Fecha de Ingreso: octubre-2010
Ubicación: $this->Mexico('Toluca');
Mensajes: 1.127
Antigüedad: 13 años, 6 meses
Puntos: 511
Respuesta: Formulario de registro en php

Hola que tal.


Te recomiendo que leas el manual, el cual te ayudará a desenvolverte en el aspecto de la programación.

http://www.php.net/manual/es/

Saludos
__________________
Recuerda que estamos aquí para orientarte, y no para hacer tu trabajo.
Si mi aporte fue de ayuda, recuerda que agradecer no cuesta nada +1

Skiper0125
  #4 (permalink)  
Antiguo 14/02/2012, 16:12
 
Fecha de Ingreso: diciembre-2011
Mensajes: 151
Antigüedad: 12 años, 3 meses
Puntos: 1
Respuesta: Formulario de registro en php

Bueno... OK! Ya hare la pregunta un poco mas... Precisa.
  #5 (permalink)  
Antiguo 17/02/2012, 13:12
 
Fecha de Ingreso: febrero-2012
Mensajes: 66
Antigüedad: 12 años, 2 meses
Puntos: 10
Respuesta: Formulario de registro en php

Lo que pides no es difícil. En principio deberás crear el form con los campos que necesitas, por ejemplo:
Código HTML:
Ver original
  1. <form method="POST" action="comprobar.php">
  2. Email<input type="text" name="email"/>
  3. Repita email<input type="text" name="repeticionEmail"/>
  4. </form>

Dentro de <form> deberías poner todos los campos que necesites como los de la contraseña
Código HTML:
Ver original
  1. <input type="password" name="pass"/>

Despues, si te da igual que la comprobación se haga en otra página, en la página comprobar.php, que es donde se mandarían los datos del formulario, haríamos la comprobaciones de esta manera:
if($_POST["email"]==$_POST["repeticionEmail"])echo "email repetido correctamente"
y el resto de comprobaciones.

Si quisieras que el formulario comprobara los datos sin cambiar de página tendría que ser mediante Javascript y Ajax.

Un saludo
  #6 (permalink)  
Antiguo 17/02/2012, 13:19
Avatar de memoadian
Colaborador
 
Fecha de Ingreso: junio-2009
Ubicación: <?php echo 'México'?>
Mensajes: 3.696
Antigüedad: 14 años, 10 meses
Puntos: 641
Respuesta: Formulario de registro en php

leer el manual de php si no sabes programación, es como leer un libro de medicina en 3ero de secundaria.

Lo mejor es tomar un curso o videotutoriales. ya cuando tengas las bases leer el código y crearlo será como flotar :)
  #7 (permalink)  
Antiguo 19/02/2012, 04:17
 
Fecha de Ingreso: diciembre-2011
Mensajes: 151
Antigüedad: 12 años, 3 meses
Puntos: 1
Respuesta: Formulario de registro en php

Justo cree un post para eso, para concretar un poco.. Lo queria comprobar en la misma pagina. En otra pagina si sabia como...

Lo tengo asi, estaria bien?
Código PHP:
Ver original
  1. if (isset($_POST) && isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] == 'http://www.elzulo***/alta_usuario.php' && !empty($_POST)) {
  2.     $username = $_POST["strNick"];
  3.     $pass = $_POST["strPassword"];
  4.     $password = $_POST["password"];
  5.     $email = $_POST["strEmail"];
  6.     $mail = $_POST["mail"];
  7.     $telefono = $_POST["intNtelf"];
  8.     $telefono2 = $_POST["telefono"];
  9.      
  10.     $checkuser = comprobaruser($_POST["strNick"]);
  11.     $checkmail = comprobaruser($_POST["strEmail"]);
  12.      
  13.           if($pass!=$password) {
  14.              echo "Las contraseñas no coinciden"; }
  15.                 if($email!=$mail) {
  16.              echo "El email no coincide"; }
  17.          
  18.              if($telefono!=$telefono2) {
  19.              echo "Los telefonos no coinciden";
  20.           }else {
  21.              if ($checkuser !=0) {
  22.                  echo "El usuario" .$username. "ya existe"; }
  23.                  
  24.                  if ($checkmail !=0){
  25.                      echo "El mail" .$email. "ya existe"; }
  26.          
  27.           }
  28.     }else {
  29.      
  30.     if (isset($_POST["form1"])) {
  31.       $insertSQL = sprintf("INSERT INTO tblusuario (strNombre, strEmail, intActivo, strPassword, strDireccion) VALUES (%s, %s, %s, %s, %s)",
  32.                            GetSQLValueString($_POST['strNombre'], "text"),
  33.                            GetSQLValueString($_POST['strEmail'], "text"),
  34.                            GetSQLValueString($_POST['intActivo'], "int"),
  35.                            GetSQLValueString($_POST['strPassword'], "text"),
  36.                            GetSQLValueString($_POST['strDireccion'], "text"));
  37.      
  38.       mysql_select_db($database_conexionzulo, $conexionzulo);}}
  #8 (permalink)  
Antiguo 19/02/2012, 18:47
 
Fecha de Ingreso: diciembre-2011
Mensajes: 151
Antigüedad: 12 años, 3 meses
Puntos: 1
Respuesta: Formulario de registro en php

Los errores que me da....

( ! ) Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\zulo\includes\funciones.php on line 333
Call Stack
# Time Memory Function Location
1 0.0013 415120 {main}( ) ..\alta_usuario.php:0
2 0.0053 529240 comprobaruser( ) ..\alta_usuario.php:49
3 0.0085 529584 mysql_num_rows ( ) ..\funciones.php:333

( ! ) Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\zulo\includes\funciones.php on line 348
Call Stack
# Time Memory Function Location
1 0.0013 415120 {main}( ) ..\alta_usuario.php:0
2 0.0090 529328 comprobarmail( ) ..\alta_usuario.php:50
3 0.0100 529672 mysql_num_rows ( ) ..\funciones.php:348

Las funciones:


// +++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++

function comprobaruser($user)
{
global $database_conexionzulo, $conexionzulo;
mysql_select_db($database_conexionzulo, $conexionzulo);
$query_ConsultaFuncion = sprintf("SELECT strNick FROM tblusuarios WHERE idUsuario = %s",$user);
$ConsultaFuncion = mysql_query($query_ConsultaFuncion, $conexionzulo);
$totalRows_ConsultaFuncion = mysql_num_rows($ConsultaFuncion);
if ($totalRows_ConsultaFuncion == 0)
return 0;

}

// +++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++

function comprobarmail($user)
{
global $database_conexionzulo, $conexionzulo;
mysql_select_db($database_conexionzulo, $conexionzulo);
$query_ConsultaFuncion = sprintf("SELECT strEmail FROM tblusuarios WHERE idUsuario = %s",$user);
$ConsultaFuncion = mysql_query($query_ConsultaFuncion, $conexionzulo);
$totalRows_ConsultaFuncion = mysql_num_rows($ConsultaFuncion);
if ($totalRows_ConsultaFuncion == 0)
return 0;

}
  #9 (permalink)  
Antiguo 20/02/2012, 09:33
 
Fecha de Ingreso: febrero-2012
Mensajes: 66
Antigüedad: 12 años, 2 meses
Puntos: 10
Respuesta: Formulario de registro en php

Esos errores son porque la consulta no se ha ejecutado correctamente, te recomiendo poner despues del mysql_query la sentencia die(mysql_error()) para ver si mysql te está devolviendo algún error.
$ConsultaFuncion = mysql_query($query_ConsultaFuncion, $conexionzulo) or die(mysql_error());
$ConsultaFuncion = mysql_query($query_ConsultaFuncion, $conexionzulo) or die(mysql_error());

Porque haces la consulta con sprintf en vez de poner una cadena normal??

Puede ser que el error esté en que estás tratando el idUsuario como string en sprintf mientras que en mysql lo tratas como un int.
  #10 (permalink)  
Antiguo 20/02/2012, 17:08
 
Fecha de Ingreso: diciembre-2011
Mensajes: 151
Antigüedad: 12 años, 3 meses
Puntos: 1
Respuesta: Formulario de registro en php

mmmmmmm.... Si ejecuto la consulta en navicat me devuelve el mail si es que existe...

Lo estoy tratando, tanto el nick como el mail son varchar...

A ver si mañana saco un poco de tiempo y me pongo a ello...

Etiquetas: formulario, html, mysql, registro, sql, usuarios
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 14:46.