Hi, DaniWeb

I'm trying to do a validation form, but when i "submit" and forgot some of the textbox's it gives the error, but erases the textebox's previously filled.

Here's the code:

<?php

include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
    $error = array();//Declare An Array to store any error message 
    
    if (empty($_POST['username'])) {//if no name has been supplied 
        $error[] = 'Please Enter a name ';//add to array "error"
    } else {
        $name = $_POST['username'];//else assign it a variable
    }


    if (empty($_POST['email'])) {
        $error[] = 'Please Enter your Email ';
    }else{
	   if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
           //regular expression for email validation
            $Email = $_POST['email'];
        } else {
             $error[] = 'Your EMail Address is invalid  ';
        }


    }


    if (empty($_POST['pass'])) {
        $error[] = 'Please Enter Your Password ';
    } else {
        $Password = $_POST['pass'];
    }


    if (empty($error)) //send to Database if there's no error '

    { // If everything's OK...

        // Make sure the email address is available:
        $query_verify_email = "SELECT * FROM alunos  WHERE email_aluno ='$Email'";
        $result_verify_email = mysql_query($connect, $query_verify_email);
        if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
            echo ' Database Error Occured ';
        }

        if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .


            // Create a unique  activation code:
            $activation = md5(uniqid(rand(), true));


            $query_insert_user = "INSERT INTO  ( username, email_aluno, password) VALUES ( '$name', '$Email', '$Password')";


            $result_insert_user = mysql_query($connect, $query_insert_user);
            if (!$result_insert_user) {
                echo 'Query Failed ';
            }

            if (mysqli_affected_rows($connect) == 1) { //If the Insert Query was successfull.


                // Send the email:
                $message = " To activate your account, please click on this link:\n\n";
                $message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
                mail($Email, 'Registration Confirmation', $message, 'From: ismaakeel@gmail.com');

                // Flush the buffered output.


                // Finish the page:
                echo '<div class="success">Thank you for
registering! A confirmation email
has been sent to '.$Email.' Please click on the Activation Link to Activate your account </div>';


            } else { // If it did not run OK.
                echo '<div class="errormsgbox">You could not be registered due to a system
error. We apologize for any
inconvenience.</div>';
            }

        } else { // The email address is not available.
            echo '<div class="errormsgbox" >That email
address has already been registered.
</div>';
        }

    } else {//If the "error" array contains error msg , display them
        
        

echo '<div class="errormsgbox"> <ol>';
        foreach ($error as $key => $values) {
            
            echo '	<li>'.$values.'</li>';


       
        }
        echo '</ol></div>';

    }
  
    mysql_close($connect);//Close the DB Connection

} // End of the main Submit conditional.

?>

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Registration Form</title>


    
    
    
<style type="text/css">
/* Box Style */


 .success, .warning, .errormsgbox, .validation {
	border: 1px solid;
	margin: 0 auto;
	padding:10px 5px 10px 50px;
	background-repeat: no-repeat;
	background-position: 10px center;
     font-weight:bold;
     width:450px;
     
}

.success {
   
	color: #4F8A10;
	background-color: #DFF2BF;
	background-image:url('images/success.png');
}
.warning {

	color: #9F6000;
	background-color: #FEEFB3;
	background-image: url('images/warning.png');
}
.errormsgbox {
 
	color: #D8000C;
	background-color: #FFBABA;
	background-image: url('images/error.png');
	
}
.validation {
 
	color: #D63301;
	background-color: #FFCCBA;
	background-image: url('images/error.png');
}



</style>

</head>
<body>


<form action="index.php" method="post" class="registration_form">
   <fieldset>
    <legend> ALUNO </legend>
     
    <br/>
    <div class="field"><label>Username*: </label><input type="text" size="30" name = "username" value = "<?php echo $_POST['username']; ?>" /></div>
    <br/>
    <div class="field"><label>Password*: </label><input type="password" size="25" name = "pass"/></div>
    <br/>
    <div class="field"><label>Confirma Password*: </label><input type="password" size="25" name = "conf_pass"/></div>
    <br/>
    <div class="field"><label>Nome*: </label><input type="text" size="40" name = "nome"/></div>
    <br/>
    <div class="field"><label>Data de Nascimento: </label><input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="3" maxlength="2" name = "dia"/> / <input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="3" maxlength="2" name = "mes"/> / <input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="5" maxlength="4" name = "ano"/> (DD/MM/AAAA)</div>
    <br/>
    <div class="field"><label>Morada: </label><input type="text" onkeypress="return onlyNumbers();" size="39" name = "morada"/></div>
    <br/>
    <div class="field"><label>Código Postal: </label><input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="5" maxlength="4" name = "cp1"/> - <input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="4" maxlength="3" name = "cp2"/></div>
    <br/>
    <div class="field"><label>Telemóvel*: </label><input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="10" maxlength="9" name = "tele"/></div>
    <br/>
    Curso*: <select name="curso">
    <option value = 1> Piano </option>
    <option value = 2> Orgão </option>
    <option value = 3> Guitarra Elétrica </option>
    <option value = 4> Guitarra Acústica </option>
    <option value = 5 Violino </option>
    <option value = 6> Canto </option>
    <option value = 7> Bateria </option>
    <option value = 8> Saxofone </option>
    <option value = 9> Flauta </option>
    <option value = 10> Baixo </option>
    <option value = 11> Violoncelo </option>
    </select>
    <br/>
    <br/>
    <div class="field"><label>E-Mail*: </label><input type="text" value="" name ="email" size = "25"/></div>
    <br/>
    Observações:
    <br/>
    <textarea cols="30" rows="7" name="obs"></textarea>
    </fieldset>
    <br/>
    <fieldset>
    <legend> ENCARREGADO DE EDUCAÇÃO </legend>
     
    <br/>
    <div class="field"><label>Nome*: </label><input type="text" size="40" name = "nome_ee"/></div>
    <br/>
    <div class="field"><label>Morada: </label><input type="text" size="39" name = "morada_ee"/></div>
    <br/>
    <div class="field"><label>Código Postal: </label><input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="5" maxlength="4" name = "cp1_ee"/> - <input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="4" maxlength="3" name = "cp2_ee"/></div>
    <br/>
    <div class="field">Telemóvel*: </label><input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="10" maxlength="9" name = "tele_ee"/></div>
    <br/>
    <div class="field"><label>E-Mail*: </label><input type="text" value="" name = "email_ee" size = "25"/></div>
     
    </fieldset>
    <br/>
    * Campos Obrigatórios
    <br/>
    <div class="submit">
     <input type="hidden" name="formsubmitted" value="TRUE" />
      <input type="submit" value="Register" />
    </div>
  </fieldset>
</form>

</body>
</html>

Can some one help me, please?

Thank you,
PF2G

Member Avatar for diafol

Clean your input variables.

Anyway:

You could do this (example for e-mail field):

...
$email="";
...

function is_email($e){
  return (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $e)) ? true : false;
}

if(isset($_POST['submit'])){
...
  if(!empty($_POST['email']) && is_mail($_POST['email'])){
     $email = mysql_real_escape_string($_POST['email']);
  }else{
     $error[] = "Email not valid";
  }
...
}
...
<div class="field"><label>E-Mail*: </label><input type="text" value="<?php echo $email;?>" name = "email_ee" size = "25"/></div>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.