我有一个用户输入数据的表单,例如名字和姓氏等。我有PHP验证,检查空字段。问题是当单击提交按钮时,当字段留空时,整个表单数据将被删除。
我在下面试过这个方法。
<input type="text" value="<?php echo $_POST["UserName"]; ?>"" name="UserName"
id="UserName" size="20" />
但是第一次加载表单时,文本框内是
<br /><b>Notice</b>: Undefined index: UserName in ...... on line <b>477</b><br />
是否有方法可以阻止表单被清除?或者将数据回显到字段中?
答案 0 :(得分:4)
替换这个:
value="<?php echo $_POST["UserName"]; ?>"
用你的代码:
<?php if(isset($_POST["UserName"])) echo $_POST["UserName"]; ?>
答案 1 :(得分:2)
这里的问题是您没有检查$ _POST [&#34; UserName&#34;]是否已初始化,如果不是,则您将抛出错误。检查isset:
<input type="text" value="<? if isset($_POST["UserName"]) { echo $_POST["UserName"]; } ?>" name="Givenname" id="Givenname" size="20" />
答案 2 :(得分:1)
检查是否$_POST["UserName"]
isset
,试试这个:
<input type="text" value="<?php echo isset($_POST["UserName"]) ? $_POST["UserName"] : ''; ?>" name="Givenname"
id="Givenname" size="20" />
答案 3 :(得分:1)
我认为你正在使用这样的重置按钮:
<input type="reset" />
试试这个:
<input type="submit" />
如果你正在尝试第二个,那么在每个输入中使用required,如:
<input required type="text" />
答案 4 :(得分:1)
您的表单未被清除或删除。但是您正在使用新表单加载新页面。
您尝试加载新表单是一个很好的表单,但您需要更改
<input type="text" value="value="<?php echo $_POST["UserName"]; ?>"" name="UserName" id="UserName" size="20" />
到
<input type="text" value="<?php echo isset($_POST["UserName"])?$_POST["UserName"]:""; ?>" name="UserName" id="UserName" size="20" />
请删除第二个value="
以及应该从未出现的相应"
。并在尝试回复之前检查变量是否可用。
除此之外,您可能还希望在服务器端验证之上在Javascript中进行客户端验证。 (顺便说一句,永远不要只做客户端验证,因为最终用户可以愚弄它。)
您可以做的是将<form>
标记更改为:
<form action="..." method="post" onsubmit="if (document.getElementById('UserName').value == '') { alert('UserName is still empty'); return false; }">
这将阻止在UserName仍为空时将表单发送到PHP。从而防止页面被重新加载并清除表单。
答案 5 :(得分:0)
PHP表单通常会在错误验证时丢弃输入的数据,即使在输入字段中回显它也会在成功提交时缓存条目,并且可以理解删除不允许的数据将是默认行为。然而,在文本区域中重新键入大量文本可能是一个真正的困难,并且它的突然消失可能会成为用户不受欢迎的意外,特别是当由于诸如超出字符数限制的简单原因时
使用错误验证设置$_POST['UserName']
值应该保留字段输入而不允许其进程。该示例使用变量来缓存数据并将其回显到输入字段中。
更新:脚本已更新为包含同一表单的多个提交按钮,以及成功消息数组的选项。
更新:脚本已更新为包含exit()选项以及textarea。
UserName使用错误数组,而First Name使用exit()停止 这个剧本一共。
文本框容差也会触发大写A-Z或错误 特殊字符,并使用exit()来停止脚本。
表单数据将保留在错误消息,exit()页面返回和成功发送。
表单结果将在成功发送时打印。
<?php
/* Define variables and set to empty values.*/
$username=$first_name=$textbox='';
/* If using non-array success variable, initialize it as a string:
$success='';
Otherwise, define as an array. */
/* Submit button is clicked, start validation.
Separate multiple submit buttons (for the same form) with || (|| = OR):
*/
if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
// Define error and success messages as arrays to display in a list.
$error=array();
$success=array();
// Validate user input and error characters not lowercase a-z or 1-9.
if (!empty($_POST['UserName'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
if (preg_match("/^[a-z0-9]+$/", $username)) {
/*
if (preg_match("/^[a-z0-9]+$/", trim($_POST['UserName']))) {
$username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
$error[]='User Name can only contain lowercase a-z and 0-9.';
$username=$username;
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether:
$username=$username;
exit ("Username may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
*/
}
}
else {
$error[]="Please enter a User Name.";
}
if (!empty($_POST['first_name'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
if (preg_match("/^[a-z0-9]+$/", $first_name)) {
/*
if (preg_match("/^[a-z0-9]+$/", trim($_POST['first_name']))) {
$first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
$first_name=$first_name;
exit ("First Name may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
/*
$error[]='First Name may only contain lowercase a-z and 0-9.';
$first_name=$first_name;
*/
}
}
else {
$error[]="Please enter a First Name.";
}
if (!empty($_POST['textbox'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", $textbox)) {
/*
if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", trim($_POST['textbox']))) {
$textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
$textbox=$textbox;
exit ("Textbox input may only contain spaces, lowercase a-z, and 0-9. Use the Back-button to try again.");
/*
$error[]='Textbox input may only contain spaces, lowercase a-z, and 0-9.';
$textbox=$textbox;
*/
}
}
else {
$error[]="Please enter Textbox content.";
}
// If no errors, process data.
if (empty($error)) {
if (isset($_POST['submit_one'])) {
/* Sanitized submit button per rule #1: never trust user input. Remove sanitization if it causes a system error.
Reiterating ($_POST['submit'] is helpful when using multiple submit buttons.
Wrap each function in the additional submit isset, and end functions with closing (empty($error) else statement. */
$_POST['submit_one']=trim(htmlspecialchars($_POST['submit_one'], ENT_QUOTES));
/* Post data or send email, and print success message.
The array is option. Do not define as an array or use[] to use as a simple variable. */
// Processing data here, for example posting to a database ...
$success[]="The submit_one Send Form request has been processed!";
}
if (isset($_POST['submit_two'])) {
$_POST['submit_two']=trim(htmlspecialchars($_POST['submit_two'], ENT_QUOTES));
// Processing data here, for example sending an email ...
$success[]="The submit_two Process Form request has been sent!";
}
}
/* If errors, show error message.
The exit() option ends the script at the validation check .*/
else {
$error[]="Please correct the errors and try again.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.wrapper {margin: 2% auto; width: 500px;}
textarea {text-align:left;}
</style>
</head>
<body>
<div id="anchor" class="wrapper">
<div>
<form name="data_form" action="#anchor" method="post">
<table>
<tr>
<td colspan="2">
<label for="UserName">User Name</label>
<br>
<input type="text" name="UserName" id="UserName" size="20" value="<?php echo $username; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="first_name">First Name</label>
<br>
<input type="text" name="first_name" id="first_name" size="20" value="<?php echo $first_name; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="textbox">Textbox</label>
<textarea name="textbox" id="textbox" style="height:100px; width:98%;text-align:left;"><?php echo $textbox; ?></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit_one" id="submit_one" value="Send Form">
</td>
<td>
<input type="submit" name="submit_two" id="submit_two" value="Process Form">
</td>
</tr>
</table>
</form>
</div>
<div>
<?php
/* Print errors as a list or print success message.
Separate multiple submit buttons with ||. */
if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
if (!empty($error)) {
echo '<h4>The form was not sent due to the following errors:</h4>
<ul>';
foreach ($error as $message) {echo '<li>'. $message . '</li>';
}
echo '</ul>';
}
/* Print success confirmations as a list for processed input. */
else {
echo '<h4>The form has been sent!</h4>
<ul>';
foreach ($success as $message) {echo '<li>'. $message . '</li>';}
/* If using a success variable without defining it as an array,
initialize it as a variable at the top of the script,
then print variable without <ul>s and foreach loop:
echo '<p>' . $success . '</p>';
*/
echo '</ul>
<h4>Processed Data:</h4>
<ul>
<li>User Name: ' . $username . '</li>
<li>First Name: ' . $first_name . '</li>
<li>Textbox: <br>' .
/* Replace $textbox new lines with <br> tags. */
nl2br($textbox) .
'</li>
</ul>';
}
/* Unset foreach loop data. */
unset($message);
}
?>
</div>
</div>
</body>
</html>