How to echo an error message next to a form field

Discussion in 'PHP' started by amedno1, May 3, 2010.

  1. #1
    Ok this is the code below for validating the first name and last name of someone who enters data into the form, lets say they are both required, so the user needs to be informed when he leaves one blank, how do I echo the error message to the user in the HTML next to the input field?

    if (empty($fname)) {
    			echo 'Please enter your firstname';
    			$error = true;
    			$output_form = true;
    		}
    			
    		if (empty($lname)) {
    			echo 'Please enter your surname';
    			$error = true;
    			$output_form = true;
    		}
    Code (markup):

    This is the HTML part of the form:

    <tr>			   
    			<th>First Name:</th>
    						<td>
    							<input type="text" name="firstname" class="medium" value= "<?php  if (!empty($fname)) echo $fname; ?>" />
    						</td>	
    					</tr>
    
    
    					<tr>
    						<th>Surname:</th>
    							<td>
    								<input type="text" name="surname" class="large" value="<?php  if (!empty($lname)) echo $lname; ?>" />
    							</td>
    					</tr>
    Code (markup):

     
    amedno1, May 3, 2010 IP
  2. Rory M

    Rory M Peon

    Messages:
    1,020
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You may be better doing that type of validation with AJAX/JS - something client side.
     
    Rory M, May 3, 2010 IP
  3. easic

    easic Active Member

    Messages:
    37
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    70
    #3
    My opinion is that is better to do both, client and server side validation (the js validation is for ordinary people, who forget a field or something like that; the php validation is for pseudo-hackers that tries to inject something, etc).

    Anyways, there are many ways to do what you want. The one I think it is easy to understand and maintain is using vectors.

    so, you create a vector of errors, like $errors = array();
    if you find an error, you add an element to that array (the index is the name of the field and the value could be the text you want to show), for example: $errors['name'] = 'This field is required';

    On the form, you can output the error next to the field: if (isset($errors['name'])) echo $errors['name'];
     
    easic, May 3, 2010 IP
  4. amedno1

    amedno1 Active Member

    Messages:
    427
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    58
    #4
    Thanks going to try that
     
    amedno1, May 4, 2010 IP
  5. amedno1

    amedno1 Active Member

    Messages:
    427
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    58
    #5
    Im not sure what it is that is wrong with my registration page tried so many different things to fix it yet it doesnt work

    Can you maybe see what I am doing wrong that I just cant seem to detect

    Thanks

    <?php
    require_once('connectvars.php');
    require_once('validate_email.php');
    
    $msg_error = array();   
    $error = false;
    $output_form = true;
    
    /**Checks if the form is submitted and processes only when submit = true**/
       if (isset($_POST['submit'])) {
       
          // Connects to the database
          $dbc = mysqli_connect('DB_HOST', 'DB_USER', 'DB_PASSWORD', 'DB_NAME')
          or die ('Error connecting to MYQSQL server.');
          
          
          /**Retrieves the data entered into the registration form
          and stores them in variables**/
          
          $title = $_POST['title'];
          $fname = trim($_POST['firstname']);
          $lname = trim($_POST['surname']);
          $country = $_POST['country'];
          $email1 = trim($_POST['email1']);
          $email2 =  trim($_POST['email2']);
          $address = trim($_POST['address']) ;
          $postcode = trim($_POST['postcode']);
          $phone = trim($_POST['phone']);
          $cellphone = trim($_POST['cellphone']);
          $pswd1 = $_POST['password1'];
          $pswd2 = $_POST['password2'];
          $output_form = false;
          
    /**Validates the form to determine for any errors b4 storing to the db**/
          
          
          
          if (empty($title)) {
             $msg_error['title'] = "Please select your title";
          }
          
          if (empty($fname)) {
             $msg_error['fname'] = "Please enter your firstname";
          }
             
          if (empty($lname)) {
             $msg_error['lname'] = "Please enter your surname";
          }
          
          if (empty($email1)) {
             $msg_error['email1'] = "Please enter your email";
          }
          
          if (empty($email2)) {
             $msg_error['email2'] = "Please re-enter the same email";
          }
             
          if (empty($address1)) {
             $msg_error['address'] = "Please enter your postal address";
          }
          
          if (empty($postcode) || !is_numeric($postcode)) {
             $msg_error['postcode'] = "Post code cannot be empty and it must be numbers only.";
          } 
          
          if (empty($phone) || !is_numeric($phone)) {
             $msg_error['phone'] = "Phone number cannot be empty and it must be numbers only.";
          }
          
          if (!empty($cellphone)) {
             if (!is_numeric($cellphone)) {
                $msg_error ['intcellphone'] = "Cell phone can only be numbers";
             }
          }
          
          if (!empty($email1) && !empty($email2)) {
             if ($email1 == $email2) { 
                if (!$result = validate_email($email1)) {
                   $msg_error['invalidemail'] = "You have entered an invalid email";
                }
                else {
                   $msg_error['mismatchemail'] = "Your emails do not match";
                }
             }
          }
          
          if (empty($pswd1) || empty($pswd2)) {
             $msg_error['pswd'] = "Please enter a value for a password";
          }
          else {
             if ($pswd1 == $pswd2) {
                $pswd = $pswd1;
             }
             else {
                $msg_error['mismatchpswd'] = "Your passwords do not match";
             }
          }
          
          if (!empty($msg_error)) {
             $error = true;
             $output_form = true;
          }
          
          /** if there are no errors then it creates a new user in the database 
             using the submitted details**/
          if (empty($msg_error)) {
             $create_user = sprintf("INSERT INTO user (UserNr, Title, FirstName, LastName, Country, Email, PostalAddress, PostalCode, Phone, Cellphone) VALUES (0, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');",
                mysqli_real_escape_string($dbc, $title),
                mysqli_real_escape_string($dbc, $fname),
                mysqli_real_escape_string($dbc, $lname),
                mysqli_real_escape_string($dbc, $country),
                mysqli_real_escape_string($dbc, $email1),
                mysqli_real_escape_string($dbc, $address),
                mysqli_real_escape_string($dbc, $postcode),
                mysqli_real_escape_string($dbc, $phone),
                mysqli_real_escape_string($dbc, $cellphone)
             );
             
             $cu_result = mysqli_query($dbc, $create_user) or trigger_error('Error saving user profile');
             
             $create_acct = sprintf("INSERT INTO account (AcctNr, AcctTypeID, Username, Password, UserNr, DateCreated) VALUES (0, 1, '%s', SHA1('%s'), 0, CURRENT_TIMESTAMP());",
                mysqli_real_escape_string($dbc, $email1),
                mysqli_real_escape_string($dbc, $pswd)
             );
             
             
             
    		 msqli_close ($dbc);
    		 
             $output_form = false;
          }
       }
          
       if($output_form) {
       ?>
       <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
          <div id="form">
                                  
             <table>
                <tr>
                   <th>Title:</th>
                      <td>
                         <select name="title" value="<?php if (!empty($title)) echo $title; ?>" >
                            <option value="null"></option>
                            <option value="Mr.">Mr.</option>
                            <option value="Mrs.">Mrs.</option>
                            <option value="Miss">Miss</option>
                            <option value="Ms.">Ms.</option>
                            <option value="Dr.">Dr.</option>
                            <option value="Prof.">Prof.</option>
                            <option value="Rev.">Rev.</option>
                            <option value="Other">Other</option>
                         </select>
                      </td>
                      <td class="error">Required: <?php if (isset($msg_error['title'])) echo $msg_error['title']; ?></td>
                </tr>
    
                <tr>
                   <th>First Name:</th>
                      <td>
                         <input type="text" name="firstname" class="medium" value= "<?php  if (!empty($fname)) echo $fname; ?>" />
                      </td>   
                      <td class="error">Required: <?php if (isset($msg_error['fname'])) echo $msg_error['fname']; ?> </td>
                </tr>
    
                   <tr>
                      <th>Surname:</th>
                         <td>
                            <input type="text" name="surname" class="large" value="<?php  if (!empty($lname)) echo $lname; ?>" />
                         </td>
                         <td class="error"> Required: <?php if (isset($msg_error['lname'])) echo $msg_error['lname']; ?> </td>
                   </tr>
                   
                   <tr>
                   <th> Country:</th>
                      <td>
                         <select name="country" selected="South Africa">
                            <option value="Afghanistan" >Afghanistan</option>
    <option value="Albania" >Albania</option>
    <option value="Algeria" >Algeria</option>
    <option value="Andorra" >Andorra</option>
    <option value="Antigua and Barbuda" >Antigua and Barbuda</option>
    <option value="Argentina" >Argentina</option>
    <option value="Iraq" >Iraq</option>
    <option value="Japan" >Japan</option>
    <option value="Jordan" >Jordan</option>
    <option value="Lebanon" >Lebanon</option>
    <option value="Somalia" >Somalia</option>
    <option value="South Africa" selected="select" >South Africa</option>
    <option value="Spain" >Spain</option>
    <option value="Syria" >Syria</option>
    <option value="Taiwan" >Taiwan</option>
                         </select>
                      </td>
                </tr>
                   
    
       
       
                <tr>
                   <th>Postal Address:</th>
                      <td>
                         <input type="text" name="address" class="large" value="<?php  if (!empty($address)) echo $address; ?>"/>
                      </td>
                      <td class="error">Required: <?php if (isset($msg_error['address'])) echo $msg_error['address']; ?> </td>
                </tr>   
                      
                
                
                <tr>
                      <th> Postal Code: </th>
                         <td>
                            <input type="text" name="postcode" value="<?php  if (!empty($postcode)) echo $postcode; ?>" />
                         </td>
                         <td class="error">Required: <?php if (isset($msg_error['postcode'])) echo $msg_error['postcode']; ?> </td>
                </tr>
                   
                <tr>
                      <th> Phone Number: </th>
                         <td>
                            <input type="text" name="phone" value="<?php if (!empty($phone)) echo $phone; ?>"/>
                         </td>
                         <td class="error">Required: <?php if (isset($msg_error['phone'])) echo $msg_error['phone']; ?> </td>
                         
                      <th> Cellphone:</th>
                         <td>
                            <input type="text" name="cellphone" />
                         </td>
                         <td class="error"> <?php if (isset($msg_error['cellphone'])) echo $msg_error['cellphone']; ?> </td>
                </tr>   
                
                <tr>
                      <th> Email: </th>
                         <td>
                            <input type="text" name="email1" class="medium" value="<?php if (!empty($email1)) echo $email1; ?>" />
                         </td>
                         <td class="error">Required: <?php if (isset($msg_error['email1'])) echo $msg_error['email1']; ?> </td>
                </tr>
                         
                <tr>
                      <th> Re-Enter Email:</th>
                         <td>
                            <input type="text" name="email2" class="medium" value="<?php if (!empty($email2)) echo $email2; ?>" />
                         </td>
                         <td class="error">Required: <?php if (isset($msg_error['email2'])) echo $msg_error['email2']; ?> </td>
                </tr>
                
                <tr>
                      <th> Password:</th>
                         <td>
                            <input type="password" name="password1" class="medium" />
                         </td>
                         <td class="error">Required: <?php if (isset($msg_error['pswd'])) echo $msg_error['pswd']; ?> </td>
                </tr>
                
                <tr>
                      <th> Re-Enter Password:</th>
                         <td>
                            <input type="password" name="password2" class="medium" />
                         </td>
                         <td class="error">Required: <?php if (isset($msg_error['pswd'])) echo $msg_error['pswd']; ?>  <?php if (isset($msg_error['mismatchpswd'])) echo $msg_error['mismatchpswd']; ?> </td>
                </tr>
                <tr>
                      <th> </th>
                         <td>
                            <input type="submit" value="submit"/>
                         </td>
                </tr>
             </table>
          </form>
          </div>
    
          
    <?php
    }
    ?>
       <div class="boxed" id="footer">
                <p>
                   This is the footer area
                </p>
             </div>
       </div>
    </body>
    </html>
    Code (markup):
     
    amedno1, May 4, 2010 IP
  6. roopajyothi

    roopajyothi Active Member

    Messages:
    1,302
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    80
    #6
    The basic thing
    If you need to echo a html here is the format:
    If you need </font> tag in a php
    Then using PHP Echo the statement goes like this
    <\"font>

    For Example
    <input type="text" name="firstname" class="medium">
    Goes as
    echo "<input type=\"text\" name=\"firstname\" class=\"medium\">";
    You can also use Print function in php
     
    roopajyothi, May 4, 2010 IP
  7. amedno1

    amedno1 Active Member

    Messages:
    427
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    58
    #7
    The problem I am having is I want to display the error messages above the or beside the input box and I also want the form to retain the entered data if the user
    entered data but something is wrong so thats not happening. The problem with using echo is I will end up having to echo the entire form which is a huge one. I have no
    doubt echo will work but is there no way I can specify where on the form the echo message is displayed?
     
    amedno1, May 4, 2010 IP
  8. roopajyothi

    roopajyothi Active Member

    Messages:
    1,302
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    80
    #8
    The place were you add the echo it will display there if error occurs!
     
    roopajyothi, May 4, 2010 IP