我有一个简单的html表单,它接受用户名和密码并将其注册到数据库中。但是,即使在提交表单之前,只要页面加载,它就会执行以下php if语句。以下是那段代码。
if (($_POST['reg_username']=="") || ($_POST['reg_password']==""))
{ ?>
<script> alert("please enter both email and password"); </script>
<? }
完整的PHP代码如下。这不是最终的代码所以我仍然没有加密密码和一切,但我只是测试它。先谢谢你们。
if (($_POST['reg_username']=="") || ($_POST['reg_password']==""))
{ ?>
<script> alert("please enter both email and password"); </script>
<? }
$reg_username=mysql_real_escape_string($_POST['reg_username']);
$reg_username=htmlspecialchars($reg_username);
$reg_password=mysql_real_escape_string($_POST['reg_password']);
$reg_password=htmlspecialchars($reg_password);
if(!empty($reg_username) && !empty($reg_password))
{
if (isset($reg_username) && isset($reg_password))
{
mysql_select_db($db, $dbconnect);
mysql_query("INSERT into students(username,password) VALUES
('$reg_username','$reg_password')");
}
}
?>
答案 0 :(得分:0)
为什么必须在PHP中包含这些标记?为什么你不单独做。这是Javascript(jQuery)的一个例子:
请注意,自从我在一分钟内编写该代码段后,可能会出现一些拼写错误和语法错误。
<script type="text/javascript">
$(document).ready(function() {
("#login_form").submit(function() {
var username = ("#selector").val();
var password = ("#password").val();
if(username == "" && password == "") {
alert("please enter both email and password");
}
}
)};
</script>
答案 1 :(得分:0)
改变这个:
if (($_POST['reg_username']=="") || ($_POST['reg_password']==""))
{ ?>
<script> alert("please enter both email and password"); </script>
<? }
进入这个:
if(isset($_POST['reg_username']) || isset($_POST['reg_password']))
{
if (($_POST['reg_username']=="") || ($_POST['reg_password']==""))
{ ?>
<script> alert("please enter both email and password"); </script>
<?php }
}
答案 2 :(得分:0)
if(isset($_POST['SubmitButtonName'])){ //check if form was submitted
unset($_POST['SubmitButtonName']);
if (($_POST['reg_username']=="") || ($_POST['reg_password']==""))
{ ?>
<script> alert("please enter both email and password"); </script>
<? }
}
请记住更改SubmitButtonName
答案 3 :(得分:0)
<script>
$(document).ready(function(){
$("#submit").click(function(){
var register_name=$('#reg_username').val();
var register_password=$('#reg_password').val();
if(register_name =="")
{
alert("please enter your name");
return false;
} else if(register_password =="")
{
alert("please enter your password");
return false;
}
else
{
return true;
}
});
});
</script>
</head>
<body>
<form action="" method="post">
Register name:<input type="text" name="reg_username" id="reg_username"><br>
Password: <input type="password" name="reg_password" id="reg_password"><br>
<input type="submit" id="submit">
</form>
</html>