Jump to content

[SOLVED] How can i echo all empty values


Odaku128

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.