What is wrong with my code?

WHAT is WRONG WHIT THIS CODE?

if (isset($_POST['submit'])) {
$errors = array();

$required_fields = array('menu_name', 'position', 'visible');
foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
$errors[] = $fieldname;
}
}
$fields_with_lengths = array('menu_name' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $errors[] = $fieldname; }
}

if (empty($errors)) {
// Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);

$query = "UPDATE subjects SET
menu_name = '{$menu_name}',
position = {$position},
visible = {$visible}
WHERE id = {$id}";
$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
// Success
$message = "The subject was successfully updated.";
} else {
// Failed
$message = "The subject update failed.";
$message .= "<br />". mysql_error();
}

} else {
// Errors occurred
$message = "There were " . count($errors) . " errors in the form.";
}
}

I have a form with ID, MENU_NAME, POSITION and VISIBLE and i’m trying to validate the form by checking if the fields are empty OR set with foreach and if i’ts empty make $errors = $fieldname… And I test IF errors is empty execute code if it has something in it don’t… but its not listening to me… Can you help me? Thank you in advance !

I think you want to use sizeof($errors) == 0 instead of empty($errors)

Can’t get it to work… here is my idea:

$errors = array();
$names = array("James","Etel","");
				
foreach($names as $name){
     if(empty($name)){
	$errors[] = "You have an unset name in your array";
	}
}

if(empty($errors)){
	echo "OK";
}else{
	echo "You have " . count($errors) . " In your form. <br />  review the folowing fields:";
         foreach ($errors as $error){
         echo $error . "<br />";
          }
}

should return error… Right?

I think you need to replace

if(empty($errors)){ 

With

if(sizeof($errors) == 0){ 

Okay, so I was incorrect, empty() should work on an array. However, I still think sizeof() is likely a better candidate, simply for the fact that empty() looks to have changed recently between 5.3 and 5.4.

I have to check the change log… but i tried with sizeof and empty it returns no error end submits the form… I should look for other single page form submission methods… right?

“” actually equals something…it equals an empty string which is totally different from an empty variable! If you check empty($name) it will NOT be empty, as it actually contains a value (that is, it contains a value of no value…I know, confusing).

Try this:

if(empty($name) || $name =='')

Wow, that’s a good attitude to take :slight_smile: You definitely always want to learn best practices early on. Now that you mention it, the simplest way of doing it would be:

if( !array_key_exists( $fieldname, $_POST ) )

That will reduce your if statement to just a single condition. Although, I think it might actually be a million millionth of a second slower…

This way it should work but if there is a value in the error array the form still gets submitted and the if statement doesn’t work…

if (isset($_POST["submit"])){
				$errors_array = array();
				$required_fields = array("menu_name", "position", "visible");
				foreach($required_fields as $fieldname){
					if(empty($_POST[$fieldname]) || $_POST[$fieldname] == "" ){
						$errors_array[] = $fieldname;
				}
				
				if(empty($errors)){ //no error
					//form validation
				}else{
					//error
				}
		}

and when i lave the menu_name field empty $errors_array[0] == manu_name string witch is not empty but php still considers it empty (line 9) and submits an empty string in the database… WHY?

BTW thanks for helping me out learning php alone is a pain… Glad I found sitepoint…

Sorry for deleting that post… the code was…functioning incorrectly… But i’m jumping to test you idea!

In your last example you’re using $errors_array but checking if(empty($errors)) - not the same variable.

By the way, in PHP empty() is true for many cases. An empty string is “empty”.


$str = '';
var_dump( empty( $str ) ); // true

This works…


$form_action = "SAME PAGE";
$field_manu_name = "About us";
$field_position = 2;
$field_visible = 1;


if (isset($form_action)){
                $errors_array = array();
                $required_fields = array($field_manu_name, $field_position, $field_visible);
					foreach($required_fields as $fieldname){
						if(empty($fieldname) || $fieldname == "" ){
							$errors_array[] = $fieldname;
						}
					}

                if(empty($errors_array)){ //no error
                    //form validation
                    echo "OK";
                }else{
                    //error
                    echo "ERROR";
                }
				
	}

But when I use it with a form something goes wrong… I have to get this working… but I need to sleep first because i’m tired I already submitted bad code 2 times sorry about that… And thanks for everyone’s help…

I rewrited the code… and now it works… see if you can spot the difference between this and the first code i submitted…



	if (isset($_POST["submit"])){
                $errors_array = array();
                $required_fields = array("menu_name", "position", "visible");
					foreach($required_fields as $fieldname){
						if(empty($_POST[$fieldname]) || $_POST[$fieldname] == "" ){
							$errors_array[] = $fieldname;
						}
					}

                //field length
                $fields_with_lengths = array("menu_name" => 30);
		                  $errors_array = check_max_field_lengths($fields_with_lengths);


                if(empty($errors_array)){
					
					//form validation
					//perform update
					$id = mysql_prep($_GET["subj"]);
					$menu_name = mysql_prep($_POST["menu_name"]);
					$position = mysql_prep($_POST["position"]);
					$visible = mysql_prep($_POST["visible"]);
					
					$query = "UPDATE subjects SET
								menu_name = '{$menu_name}',
								position = '{$position}',
								visible = '{$visible}'
								WHERE id = {$id}";
					$result = mysql_query($query, $connection);
						if(mysql_affected_rows() == 1){ //mysql query test
							//success
							$message = "The subject was successfully updated";
							
						}else{
							//errors
							$message = "The subject update failed.";
							$message .= "<br />" . mysql_error();
						}
					
                }else{
						//errors
						if(count($errors) == 1){
							$message = "there was an error in the submitted form";
						}else{
							$message = "There were " . count($errors_array) . " errors in the form";
						}
                }
				
	}


And here is a simple version of the code…


<?php
if (isset($_POST["submit"])){
                $errors_array = array();
                $required_fields = array("username");
					foreach($required_fields as $fieldname){
						if(empty($_POST[$fieldname]) || $_POST[$fieldname] == "" ){
							$errors_array[] = $fieldname;
						}
					}

                if(empty($errors_array)){ //no error
                    //form validation
                    echo "OK";
                }else{
                    //error
                    echo "ERROR";
                }
				
	}
?>

<!--fun.php is the _self -->
<form name="input" action="fun.php" method="POST">
Username: <input type="text" name="username" />
<input name="submit" type="submit" value="Submit" />
</form>