Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to show errors in html if outputting in php

Posted on 2016-09-03
8
Medium Priority
?
60 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
8 Comments
 
LVL 59

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
 
LVL 1

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
 
LVL 1

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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

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
 
LVL 59

Accepted Solution

by:
Julian Hansen earned 2000 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
 
LVL 1

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 59

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
 
LVL 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

722 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