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";
}
?>