【发布时间】:2014-04-05 14:26:39
【问题描述】:
我正在使用 php 和 HTML 对表单进行验证。我的 HTML 代码如下所示:
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body style="background-color:#F2F2F2">
<form name="htmlform" method="post" action="test1.php" >
<table width="550px" table align="center" frame="box" height="80%" style="margin- top:25px;margin-bottom:25px; background-color:#ffffff;border-radius:5px;">
</tr>
<tr>
<th colspan="2">
<h3 align="center">Write to Us</h3>
<hr>
</th>
</tr>
<tr>
<td valign="top">
<label for="name">Name </label>
</td>
<td valign="top">
<input type="text" name="name" maxlength="50" size="30">
<span class="error">* <?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td valign="top">
<label for="email">Email Address </label>
</td>
<td valign="top">
<input type="text" name="email" maxlength="80" size="30">
<span class="error">* <?php echo $emailErr;?></span>
</td>
</tr>
<tr>
<td valign="top">
<label for="telephone">Telephone Number</label>
</td>
<td valign="top">
<input type="text" name="telephone1" maxlength="30" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="message">Message </label>
</td>
<td valign="top">
<textarea name="message1" maxlength="1000" cols="25" rows="6"></textarea>
<span class="error">* <?php echo $messageErr;?></span>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center;">
<input type="submit" value="Submit" >
</td>
</tr>
</table>
</form>
</body>
我的 PHP 代码如下所示:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["telephone1"]))
{$telephone1 = "";}
else
{$telephone1 = test_input($_POST["telephone1"]);}
if (empty($_POST["message1"]))
{$messageErr = "Message is required";}
else
{$message1 = test_input($_POST["message1"]);}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $telephone1;
echo "<br>";
echo $message1;
?>
当我尝试在名称、电子邮件、消息字段为空时显示这些错误消息时,它只会进入 test1.php 页面并显示空白数据,尽管注册表单中的字段为空。我正在使用 XAMP 服务器来执行我的文件。
提前致谢。
【问题讨论】:
-
两个代码都在同一个php中吗?即 test1.php?
-
尝试在 html 代码上方的同一文件中使用您的 php 代码,并将表单操作留空
-
php 在不同的文件中,html 在另一个文件中。如果我必须在 html 的同一个文件中使用 php 如何使用
-
如果文件名是html,将其重命名为php,然后将代码粘贴到页面顶部。就是这样。