Foros del Web » Programando para Internet » PHP »

Registro usuario

Estas en el tema de Registro usuario en el foro de PHP en Foros del Web. Hola a todos! Quisiera saber si me puden ayudar a poder mejorar este codigo que tengo de un registro de usuarios. Quiero que cuando haga ...
  #1 (permalink)  
Antiguo 21/08/2010, 22:49
Avatar de ale_dla  
Fecha de Ingreso: abril-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 189
Antigüedad: 15 años
Puntos: 3
Registro usuario

Hola a todos!
Quisiera saber si me puden ayudar a poder mejorar este codigo que tengo de un registro de usuarios.
Quiero que cuando haga click en el boton aparezca los campos de texto en color rojo y un mensaje de error.
Este es mi codigo:
Código PHP:
<?php
//signup.php
include 'connect.php';
include 
'header.php';

echo 
'<h3>Sign up</h3><br />';

if(
$_SERVER['REQUEST_METHOD'] != 'POST')
{
    
/*the form hasn't been posted yet, display it
      note that the action="" will cause the form to post to the same page it is on */
    
echo '<form method="post" action="">
          Username: <input type="text" name="usuario" /><br />
         Password: <input type="password" name="password"><br />
        Password again: <input type="password" name="user_pass_check"><br />
        E-mail: <input type="email" name="email"><br />
         <input type="submit" value="Registrarme" />
      </form>'
;
}
else
{
    
/* so, the form has been posted, we'll process the data in three steps:
        1.    Check the data
        2.    Let the user refill the wrong fields (if necessary)
        3.    Save the data 
    */
    
$errors = array(); /* declare the array for later use */
    
    
if(isset($_POST['usuario']))
    {
        
//the user name exists
        
if(!ctype_alnum($_POST['usuario']))
        {
            
$errors[] = 'The username can only contain letters and digits.';
        }
        if(
strlen($_POST['usuario']) > 30)
        {
            
$errors[] = 'The username cannot be longer than 30 characters.';
        }
    }
    else
    {
        
$errors[] = 'The username field must not be empty.';
    }
    
    
    if(isset(
$_POST['password']))
    {
        if(
$_POST['password'] != $_POST['user_pass_check'])
        {
            
$errors[] = 'The two passwords did not match.';
        }
    }
    else
    {
        
$errors[] = 'The password field cannot be empty.';
    }
    
    if(!empty(
$errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
    
{
        echo 
'Uh-oh.. a couple of fields are not filled in correctly..<br /><br />';
        echo 
'<ul>';
        foreach(
$errors as $key => $value/* walk through the array so all the errors get displayed */
        
{
            echo 
'<li>' $value '</li>'/* this generates a nice error list */
        
}
        echo 
'</ul>';
    }
    else
    {
        
//the form has been posted without, so save it
        //notice the use of mysql_real_escape_string, keep everything safe!
        //also notice the sha1 function which hashes the password
        
$sql "INSERT INTO
                    usuarios(usuario,password, email ,fecha_registro, usuario_nivel)
                VALUES('" 
mysql_real_escape_string($_POST['usuario']) . "',
                       '" 
sha1($_POST['password']) . "',
                       '" 
mysql_real_escape_string($_POST['email']) . "',
                        NOW(),
                        0)"
;
                        
        
$result mysql_query($sql);
        if(!
$result)
        {
            
//something went wrong, display the error
            
echo 'Something went wrong while registering. Please try again later.';
            
//echo mysql_error(); //debugging purposes, uncomment when needed
        
}
        else
        {
            echo 
'Succesfully registered. You can now <a href="signin.php">sign in</a> and start posting! :-)';
        }
    }
}

include 
'footer.php';
?>
Quien pueda ayudarme se los agradezco mucho!
Gracias.
  #2 (permalink)  
Antiguo 21/08/2010, 23:18
Avatar de camsworksinc  
Fecha de Ingreso: julio-2008
Ubicación: Queretaro
Mensajes: 261
Antigüedad: 15 años, 9 meses
Puntos: 11
Respuesta: Registro usuario

La mejor manera de validar datos de una forma es ANTES de ser enviada mediante JavaScript.
Por ejemplo, si tu forma tiene el campo de texto de usuario:
Código HTML:
Ver original
  1. <form id="forma" onsubmit="verificaforma()" action="script.php" method="post">
  2. <input type="text" id="usuario" name="usuario" />
  3. <input type="submit" />
  4. </form>

La funcion verificaforma() en JavaScript haria lo siguiente:
Código Javascript:
Ver original
  1. function verificaforma(){
  2. var objeto=document.getElementById("usuario");
  3.  
  4. if (objeto.value="")
  5.  {
  6.    objeto.style.background="#FF0000" //Ponemos el fondo de la caja de texto en rojo
  7.    objeto.focus() //Ponemos el cursor en el campo que necesita ser modificado
  8.   alert("El campo de usuario no puede estar en blanco!");
  9.   return false;
  10.  }
  11. else
  12.   return true;
  13. }

Si lo haces con PHP como lo intentas hacer, dado que el formulario ya fue enviado, tendrias que volver a generar la pagina del formulario ahora marcando los campos que son incorrectos, lo que implica mas trabajo y que el usuario tiene que volver a cargar otra vez la pagina.

Suerte!
__________________
¡Malditas computadoras que siempre hacen lo que les DIGO que hagan, no lo que QUIERO que hagan!
  #3 (permalink)  
Antiguo 22/08/2010, 10:22
Avatar de ale_dla  
Fecha de Ingreso: abril-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 189
Antigüedad: 15 años
Puntos: 3
Respuesta: Registro usuario

Gracias camsworksinc!
Osea que es mas conveniente hacerlo mas con jquery para validar formulario que con php.
Con php haria directamente el registro y con jquery valido los campo¿.
Seria eso no?
Bueno gracias por la respuesta.
  #4 (permalink)  
Antiguo 22/08/2010, 10:41
Avatar de carlos_belisario
Colaborador
 
Fecha de Ingreso: abril-2010
Ubicación: Venezuela Maracay Aragua
Mensajes: 3.156
Antigüedad: 14 años
Puntos: 461
Respuesta: Registro usuario

Cita:
Iniciado por ale_dla Ver Mensaje
Gracias camsworksinc!
Osea que es mas conveniente hacerlo mas con jquery para validar formulario que con php.
Con php haria directamente el registro y con jquery valido los campo¿.
Seria eso no?
Bueno gracias por la respuesta.
no lo mas conveniente es hacerlo en ambas partes xq que pasa si el usuario no tiene javascript activado?? te quedas sin validacion???? entonces debes validar tanto en el cliente como en el servidor suerte
__________________
aprende d tus errores e incrementa tu conocimientos
it's not a bug, it's an undocumented feature By @David
php the right way
  #5 (permalink)  
Antiguo 22/08/2010, 12:56
Avatar de ale_dla  
Fecha de Ingreso: abril-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 189
Antigüedad: 15 años
Puntos: 3
Respuesta: Registro usuario

Muchas gracias amigos por sus respuestas me ha servido mucho!
Saludos!

Etiquetas: registro, 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 10:43.