我正在使用.html和.php。默认情况下.html用户必须输入一些信息,当单击按钮时,html 会向 default2.php 发布。在 default2 中.php检查数据,如果数据正确,则会将用户重定向到另一个页面。我遇到的问题是输入的数据是错误的。我在这里有两个问题:
- 当数据错误时,我将用户重定向到默认值.html,因为如果我不这样做,它将保持默认值 2.php而 default2.php 对用户来说没有什么重要的东西。我不知道这是否是最好的方法。
- 当输入的数据错误时,我希望默认向用户发送回显消息.html。但是我不知道如何从默认2.php触发它。
如何解决这两个问题?谢谢。。。
默认值.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP4</title>
<style type="text/css">
body {
background-color: #CCC;
}
</style>
</head>
<body>
<p> </p>
<form id="form1" name="form1" method="post" action="default2.php">
<p>
<label for="textfield1">User Name</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="textfield2">Password</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="submit" name="button1" id="button1" value="Submit" />
<br />
<br />
<label id="label1">
</label></p>
<p> </p>
</form>
<p> </p>
</body>
</html>
默认值2.php:
<?php
require 'connection.php';
if (isset($_POST['button1'])) {
$username_v = $_POST['username'];
$password_v = $_POST['password'];
// Then you can prepare a statement and execute it.
$stmt = $dbh->prepare("CALL login(?, ?)");
$stmt->bindParam(1, $username_v, PDO::PARAM_STR);
$stmt->bindParam(2, $password_v, PDO::PARAM_STR);
// call the stored procedure
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
}
else
{
header("Location: default.html");
}
}
?>
只需添加一些参数即可
header("Location: default.html?test=failed");
在html中使用Javascript在变量测试设置为失败时显示一些合理的内容。你可以在这里找到一个教程,如何使用javascript获取url参数的值。
希望有帮助。
除此之外,您可以在default.html
中使用PHP
,甚至可以在不离开页面并突出显示验证错误的情况下AJAX
请求进行验证。
就个人而言,我不喜欢使用查询字符串向用户公开"错误"和"无效"等状态。在这种情况下,我会将两个文件合并到一个 PHP 文件中,PHP 代码在顶部,HTML 代码在底部。
PHP 代码中的if
语句是:
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
exit;
}
else
{
$error = true;
}
在要显示消息的 HTML 中:
<?php
if( isset( $error ) && $error )
echo 'You have entered the wrong data!';
?>
当然,在表单元素中,您必须删除 action="default2.php"
.
如果您希望将逻辑和标记分开,则可以将default.html
更改为例如template.php
并将其包含在控制器 php 文件的末尾。
我只是不喜欢没有任何内容的额外页面的想法,这些页面仅充当重定向器。
如果你默认.html一个PHP文件,你可以通过URL传递一个变量,这将允许你检查这个变量是否已使用$_GET[]
传递,并向用户显示一条消息。
例如,如果您将用户转发到
默认值.php?错误=1
在默认页面上,您可以有一段代码,例如
if (isset($_GET['error'])) {
echo "Show user a message here";
}