3

I'm trying to learn validation and below is where a form for user to enter the 4 fields which I need to validate the user's entry.

1st question: For the variable $a to check if there's content in error array, where should I define it ?

2nd question: for each field(productname/desc/cat/price), should i create a different array to store the error message ?

<?php

$productName = filter_has_var(INPUT_GET, 'pName') ? $_GET['pName']: null;
$desc = filter_has_var(INPUT_GET, 'description') ? $_GET['description']: null;
$cat = filter_has_var(INPUT_GET, 'category') ? $_GET['category']: null;
$pPrice = filter_has_var(INPUT_GET, 'price') ? $_GET['price']: null;

$productName = trim ($productName);
$desc = trim ($desc);
$cat = trim ($cat);
$pPrice = trim ($pPrice);

echo "<h1>Product details</h1>\n";

$nameerror = array();

if (empty($productName))
{ 
$nameerror[] = "You have not enter a Product";
}
elseif (strlen($productName) >50)
{
$nameerror[] = "Exceed product field length"; 
}
if (empty($desc))
{ 
$nameerror[] = "You have not enter description in the Description field";
}
elseif (strlen($desc) >100)
{
$nameerror[] = "Exceed descrption field length"; 
}
if (empty($cat))
{ 
$nameerror[] = "You have not enter category in the Category field";
}
if (empty($pPrice))
{ 
echo"<p>You have not enter price in the Price field</p>\n";
}
elseif (strlen($pPrice) >10)
{
echo"<p>Exceed price field length</p>\n"; 
}

if (!empty($nameerror))
for ($a=0;$a<count($nameerror);$a++)
{
    echo "$nameerror[$a] <br />\n";
}
else
{
echo "<p>Name: $productName</p>\n";
echo "<p>Description: $desc</p>\n";
echo "<p>Category: $cat</p>\n";
echo "<p>Price: $pPrice</p>\n";
}

?>
2
  • 2
    $errors not defined.. Commented Nov 12, 2015 at 8:15
  • Please see this answer on how to validate and sanitize input fields. Commented Nov 12, 2015 at 9:07

1 Answer 1

3

Your aim is to collect all the errors in the form and tell the user of those.

Everything is correct except that you are using the wrong array name in your loop. It should be:

for ($a=0;$a<count($nameerror);$a++)
{
    echo "$nameerror[$a] <br />\n";
}

Answer to your second question is: No - you can store all your error messages in a single array just as you have already done.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.