Solved

How to show errors in html if outputting in php

Posted on 2016-09-03
8
23 Views
Last Modified: 2016-09-03
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
Comment
Question by:Black Sulfur
  • 5
  • 3
8 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41782992
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
 

Author Comment

by:Black Sulfur
ID: 41783051
My editor is giving me a parse error on this line:

 $email = empty($_POST['email'] ? false : $_POST['email'];
0
 

Author Comment

by:Black Sulfur
ID: 41783052
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
 

Author Comment

by:Black Sulfur
ID: 41783059
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41783070
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
 

Author Comment

by:Black Sulfur
ID: 41783079
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41783216
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
 

Author Comment

by:Black Sulfur
ID: 41783404
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now