【发布时间】:2016-10-24 03:50:07
【问题描述】:
我正在开发一个 PHP 项目,我要提交以下表单:
<h2>Create Subject</h2>
<form action="create_subject.php" method="post">
<p>Subject name:
<input type="text" name="menu_name" value="" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
for ($count=1; $count <= ($subject_count + 1); $count++) {
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" /> No
<input type="radio" name="visible" value="1" /> Yes
</p>
<input type="submit" name="submit" value="Create Subject" />
</form>`
在 create_subject.php(表单操作发生的地方)中,我进行了一些验证,如下所示:
if(isset($_POST['submit'])) {
// Process the form
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
//validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
if(!empty($errors)) {
$_SESSION["errors"] = $errors;
redirect_to("new_subject.php");
}
验证存在应该起到检查字段是否为空的作用,如下所示:
function validate_presences($required_fields) {
global $errors;
foreach ($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field)." can't be blank";
}
}
}
但是,当我提交缺少数据的表单时,我没有重定向回上一页并列出会话中存储的所有错误,而是收到以下错误消息:
注意:未定义索引:可见于 /Users/eak/Sites/widget_corp/public/create_subject.php 第 10 行
注意:未定义索引:在 /Users/eak/Sites/widget_corp/includes/validation_functions.php 上可见
第 22 行- 警告:无法修改标头信息 - 标头已由(输出开始于
/Users/eak/Sites/widget_corp/public/create_subject.php:10) 在
/Users/eak/Sites/widget_corp/includes/functions.php 在第 4 行
所以输出开始于 $_POST["visible"] 被检测为未定义的位置。这里有什么解决办法?
【问题讨论】:
-
你可以通过一些研究为你节省一些时间;你不必写这么详细的问题。如果有人没有在单选框中选择任何选项并提交表单,您将看到您所看到的错误。请看php.net/isset
-
是的,但是我怎样才能做到这一点,而不是通过错误消息停止脚本,它只是简单地重定向到上一页并在那里列出错误消息?
-
建议:只需在单选元素中预先选择是或否即可。 (如果已设置,还要检查服务器端)
-
我认为错误是由于 create_subject.php 中使用的 (int) 造成的,请在没有 int 的情况下检查一次
-
在没有 (int) 的情况下尝试过,同样的事情发生了......
标签: php html forms validation undefined-index