我正在使用来自html表单的输入来输出包含输入值的数组。我想执行基本的错误处理,指出哪些字段保留为空,如果没有输入任何字段然后输入所有的字段,则会显示一条错误消息。但是,我的代码没有按照我的意愿进行。它可以在我的代码的其他地方工作,但是我无法弄清区别。
编辑:
我收到“通知:未定义索引:ageChoice”和“通知:未定义索引:colourChoice”
的HTML
<form action="profileFilter.php" method="POST">
<p>Age: <br>
<input type="radio" name="ageChoice" value="1">1
<input type="radio" name="ageChoice" value="2">2
<p>Colour: <br>
<input type="radio" name="colourChoice" value="Tabby">Tabby:
<input type="radio" name="colourChoice" value="Ginger">Ginger
<input type="submit" name="button">
</form>
ProfileArray.class.php
class ProfileArray {
Public function dataArray() {
$profileArray = array(
array( 'Name' => 'Toby',
'Age' => 3,
'Colour' => 'Ginger',
'Gender' => 'Male',
'Personality' => 'Gentle',
),
array( 'Name' => 'Cassie',
'Age' => 2,
'Colour' => 'Tabby',
'Gender' => 'Female',
'Personality' => 'Playful',
),
);
return $profileArray;
}
}
profileFilter.php
include ("ProfileArray.class.php");
$object = new ProfileArray();
$profileArray = $object->dataArray();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$passedAgeChoice = $_POST['ageChoice'];
$passedcolourChoice = $_POST['colourChoice'];
$errorMessage = "";
if (!empty($passedAgeChoice)) {
echo $errorMessage = "WARNING: You have not entered an age to search for<br>";
}
if (!empty($passedColourChoice)) {
echo $errorMessage = "WARNING: You have not entered a colour to search for<br>";
}
if ($errorMessage == TRUE) {
echo '<h4 class="error">You have inputted nothing to search for</h4><a href="catMatch.html" class="error_button"> Go back and try again</a>';
}
//If there are no errors submit the form
if ($errorMessage == "") {
echo '<h4 class="error">Here are your full search results</h4><a href="catMatch.html" class="error_button"> Back to Homepage</a><br>';
}
}
最佳答案
对此处的所有内容都使用isset()
和!isset()
,您不会收到任何警告。正如我在评论中提到的,isset()
最好用于单选按钮(和复选框)。
empty()
主要用于字符串输入,长度等。旁注:
$passedcolourChoice
也已替换为$passedColourChoice
。变量区分大小写。
您可以省略
$passedAgeChoice = $_POST['ageChoice'];$passedcolourChoice = $_POST['colourChoice'];
并使用以下代码:if(isset($_POST['ageChoice'])){
$passedAgeChoice = $_POST['ageChoice'];
}
if(isset($_POST['colourChoice'])){
$passedColourChoice = $_POST['colourChoice'];
}
$errorMessage = "";
if (!isset($passedAgeChoice)) {
echo $errorMessage = "WARNING: You have not entered an age to search for<br>";
}
if (!isset($passedColourChoice)) {
echo $errorMessage = "WARNING: You have not entered a colour to search for<br>";
}
if ($errorMessage == TRUE) {
echo '<h4 class="error">You have inputted nothing to search for</h4><a href="catMatch.html" class="error_button"> Go back and try again</a>';
}
关于php - PHP : REQUEST_METHOD as basic error handling for html form,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37604467/