我正在尝试学习验证,下面是用户输入4个字段的表单,该字段用于验证用户的输入.
第一个问题:要让变量$a检查错误数组中是否有内容,应在哪里定义?
第二个问题:对于每个字段(产品名称/描述/猫/价格),我应该创建一个不同的数组来存储错误消息吗?
<?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";
}
?>
解决方法:
您的目的是收集表格中的所有错误并将这些错误告知用户.
一切都正确,除了在循环中使用错误的数组名称.它应该是:
for ($a=0;$a<count($nameerror);$a++)
{
echo "$nameerror[$a] <br />\n";
}
第二个问题的答案是:否-您可以像已经完成的那样将所有错误消息存储在单个数组中.