我正在尝试将必填字段验证添加到有 5 个同名单选按钮的页面。如果用户单击按钮进入下一页,则应显示错误,以下是我当前正在使用的代码,但它没有做任何事情
<?php
if (empty($_POST) === false) {
$required_fields = array('q1');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Please select a number between 1-5';
break 1;
}
}
if (empty($errors) === true) {
if(!isset($_POST['q1'])){
$errors[] = "Please select a number between 1-5";
}
}
}
?>
<h1>Assessment</h1>
<?php
if (isset($_GET['success']) && empty($_GET['success'])) {
} else {
if (empty($_POST) === false && empty($errors) === true) {
$updateassessment = array(
'q1' => $_POST['q1'],
);
updateassessment($updateassessment);
header ('Location: question2.php');
exit();
} else if(empty($errors) === false){
echo output_errors($errors);
}
?>
<form action="" method="post">
<p class="p1">
Question 1</p>
<p class="p4">
<?php
$result = mysql_query("SELECT * FROM traits WHERE Question = 'q1'");
while($row = mysql_fetch_array($result))
{
echo $row['fromtrait'] . ' - ' . $row['totrait'];
echo "<br />";
}
?></p>
<p class="p3">
<input type="radio" name="q1" value="1" />
1
<input type="radio" name="q1" value="2" />
2
<input type="radio" name="q1" value="3" />
3
<input type="radio" name="q1" value="4" />
4
<input type="radio" name="q1" value="5" />
5
</p><br><br>
<input type="image" src="Images/image1.png" name="submit" align="right"/>
</form>
我通过添加使这个工作
if (empty($errors) === true) {
if(!isset($_POST['q1'])){
$errors[] = "Please select a number between 1-5";
}
}