Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 69
  • Last Modified:

How to show errors in html if outputting in php

Sorry if the title doesn't make sense but I didn't quite know how else to word it.

I am trying to display errors in the way that makes sense most to me. I am going to use a simple example of the email field being empty or invalid and then doing something if there are errors or doing something else if not. I don't want to just echo the error in this php code otherwise it won't show up where I want it so I have it called in the html. In my previous question, Julian suggested that I should close off the code if even the first condition is not met, before carrying on to the second. I would also just like to get some clarity on how to do that properly.

 if (!$_POST['email']) {
        $error .= "You must enter an email address";	  
      }

// CLOSE ABOVE IF FIELD IS EMPTY AS TO NOT EXECUTE ANY FURTHER CODE?

     if ($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
        $error .= "Email invalid";
      }  
    // CLOSE ABOVE IF FIELD IS EMPTY AS TO NOT EXECUTE ANY FURTHER CODE?

		if ($error) {
			
			// I WANT TO DISPLAY $error IN THE HTML FORM BELOW SUBMIT BUTTON
			}
		
		else {
		
      // SET VARIABLES AND DO SOMETHING WITH THE EMAIL ADDRESS


This is in the html form underneath the submit button: 

[code]<div class="alert-danger"><?php echo $error; ?></div>

Open in new window

0
Black Sulfur
Asked:
Black Sulfur
  • 5
  • 3
1 Solution
 
Julian HansenCommented:
First up I would put all of this code in a separate file and then simply include it on my form page

validate.php
$error = "";
// CHECK FOR A FORM POST
if ($_POST) {
  // GET THE TOKEN FROM THE POST
  $token = isset($_POST['token']) ? $_POST['token'] : false;
  
  // DID WE GET A TOKEN?
  if ($token) {
    // DOES IT MATCH OUR SESSION TOKEN
    if ($token == $_SESSION['token']) {
      // DID WE GET AN EMAIL ADDRESS
      $email = empty($_POST['email') ? false : $_POST['email'];
      // YES - UPDATE USER ACCOUNT
      if ($email) {
        $error .= updateUserAccount($email);
      }
      // NO - ADD TO ERROR
      else {
        $error .= "You must enter an email address";
      }
    }
    else {
      // HANDLE INVALID TOKEN HERE
    }
  }
  else {
    // HANDLE NO TOKEN HERE
  }
}  

// SET NEXT TOKEN
$_SESSION['token'] = md5(uniqid(mt_rand(), true));

function updateUserAccount($email)
{
  // INITIALISE THE RETURN STRING
  $ret = '';
  
  // CHECK FOR A VALID EMAIL ADDRESS AND SET RETURN IF INVALID
  if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    $ret = "Email invalid";
  }
  // ATTEMPT TO UPDATE USER VALIDATION CODE
  else {
    $sql = "SELECT userID FROM `users` WHERE email = '" . $link->real_escape_string($email) . "'";
    $result = $link->query($sql);
  // WE GOT A VALID RESPONSE SO UPDATE USER CODE
    if ($result->num_rows == 1) {
      $validation_code = md5($email + microtime());
      setcookie('temp_access_code', $validation_code, time() + 60);
      $sql = "UPDATE `users` SET identifier = '".$link->real_escape_string($validation_code)."' WHERE email = '".$link->real_escape_string($email)."'";
      $result = $link->query($sql);
      $subject = "Please reset your password";
      $message = "Here is your password reset code {$validation_code}. Click here to reset your password http://localhost:8888/simpleblog/code.php?email=$email&code=$validation_code";
      // LOOKS SOME EMAIL CODE GOES HERE?
    } 
  // SOMETHING WENT WRONG WITH THE DB UPDATE SO SET RETURN
  // MSG ACCORDINGLY
    else {
      $ret = "Request failed. Please contact an administrator";
    }
  }
  
  // RETURN OUR STATUS
  return $ret;
}

Open in new window

form.html
require_once "validate.php";

Open in new window


As to how you would display in the HTML form
You could do something like this (assumes Bootstrap)

<input type="submit" "Button here" />
<?php if ($error !== '') : ?>
<div class="alert alert-danger"><?php echo $error;?></div>
<?php endif;?>

Open in new window

Note the conditional display of the alert <div> with the error based on whether $error is empty or not.
0
 
Black SulfurAuthor Commented:
My editor is giving me a parse error on this line:

 $email = empty($_POST['email'] ? false : $_POST['email'];
0
 
Black SulfurAuthor Commented:
Oh, and I see you are using the code from the previous question :)

Could you just use the code I posted in this question just so I can look at it from a simpler point of view. I think if I break this into little bits it might be easier for me to understand.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Black SulfurAuthor Commented:
I had actually done this before you posted your solution. Would this be okay?

$err = "";
$success = "";

if ($_SERVER['REQUEST_METHOD'] == "POST") {
	
	$email = $link->real_escape_string($_POST['email']);
	$pwd = $link->real_escape_string($_POST['pwd']);
	$vwd = $link->real_escape_string($_POST['vwd']);
	
	
	if (!$email) {
		
		$err .="email can't be empty<br>";
	}
	
	
 if ($pwd != $vwd) {
	 
	 $err .= "passwords did not match!<br>";
 }
	
	if ($err) {
		
		$err;
	}
	
	else {
		
		$success;
		
	}
	
	
}

Open in new window


Then I could just display $error & $success in the html.
0
 
Julian HansenCommented:
The problem with the code above is that assumes that $_POST['email'], $_POST['pwd'] and $_POST['vwd'] exist - which is not guaranteed.

You should do something like
$email = isset($_POST['email']) ? $_POST['email'] : false;
$pwd= isset($_POST['pwd? $_POST['pwd'] : false;
$vwd= isset($_POST['vwd? $_POST['vwd'] : false;

Open in new window


Otherwise you have the basic idea.

I would move your validation off into a function like I did in my earlier post and then put that in a separate include - just to neaten things up but it is your call.
0
 
Black SulfurAuthor Commented:
Cool, thanks. I am trying to get my head around function as that does seem like a better way to do things but I think I will just do it like this for now and once I can get this right I will move onto functions.

The main thing I wanted to check was if this part was okay. Is it acceptable to do this or not?

if ($err) {
		
		$err;
	}

Open in new window


That's the only thing I could think of to not echo out the error there but I had to put something in there.
0
 
Julian HansenCommented:
Actually that entire if statement won't really do anything.

The variables in the statement blocks don't do anything on their own.

Unless you are going to put an echo in there or some other logic to change the state of the application - no reason for that block to be there.

To answer your question though - for an if statement - if there is nothing to do on true then flip the condition and check for the false value and then don't do an else. i.e.

if (!$err) {
   // Do something for success
}
// otherwise let execution drop through
1
 
Black SulfurAuthor Commented:
I see. I didn't realise you could let it just execute without having to give it something to do hence me doing what seemed to be a waste of time which you just confirmed! Awesome, I get it now (hopefully) ;)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 5
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now