Jump to content

Recommended Posts

Hi,

I need help with the following code:

 

<?php

 

foreach($_POST as $key => $val) {

if(empty($val)) {

 

$errors .= "$key is empty<br />";

 

echo $errors;

 

exit;

 

}

}

 

My form posts several keys and this code is to check if the values are empty. $errors is supposed to echo all empty values but at present will only echo the first empty value it come across.

 

What have i done wrong?

Link to comment
https://forums.phpfreaks.com/topic/181734-solved-how-can-i-echo-all-empty-values/
Share on other sites

The reason it only echos the first is you have exit;

 

Remove that line and it will show all errors. Exit does at it suggests and exit's the script completely. You may have been looking for continue; instead, which will continue the loop. (Only needed if you do not want to proceed with the current loop item if an error is found.)

If i then send it to another page how can i get it to echo all the empty values there?

 

<?php

 

foreach($_POST as $key => $val) {

if(empty($val)) {

 

$errors .= "$key is empty<br />";

 

session_start();

$_SESSION['Form Errors'] = "$errors";

Header('Location: ../somewhere.php');

exit;

session_destroy();

 

}

}

<?php
session_start();
foreach($_POST as $key => $val) {
    if(empty($val)) {
         $errors .= "$key is empty<br />";
    }
}         

// lets make sure we have error data first 
if (strlen($errors) > 0) {
     $_SESSION['Form Errors'] = $errors;
}
Header('Location: ../somewhere.php');
?>

 

Somewhere.php:

<?php
session_start();

if (isset($_SESSION['Form Errors'])) {
     echo "The following errors have been encountered: <br />" . $_SESSION['Form Errors'];
}else {
     echo "Thank you for submitting your data error free!";
}
?>

 

Exit is not needed in how you have been using it, php will exit itself automatically.

 

And also, calling session_destroy after setting a session value is contradictive, as it will destroy the session before you get to use it...so there was no point to set a session variable in the first place.

 

EDIT:

Just added an else at the end of somewhere.php

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.