我创建了一个登录表单,我遇到了很多其他问题,现在我发现PHP代码正在执行之前 提交。如何解决问题?由于PHP不支持onclick事件(无论如何都很糟糕!),我看不到任何我知道的解决方案!
代码:
//Get the form with POST
$user = mysql_real_escape_string($_POST['user']);
$password = mysql_real_escape_string($_POST['pass']);
$usernames=mysql_query("SELECT * FROM user_info WHERE Username='" . $_POST['user'] . "' AND Password='" . $_POST['pass'] . "'");
if(!$usernames){echo mysql_error();}
$count=mysql_num_rows($usernames);
if(!$count){echo mysql_error();}
//If $count is equal to one, register the user and redirect him to his page, or else echo him that his info is wrong
if($count === 1) {
$_SESSION['code'] = "titan";
$_SESSION['ande'] = $user;
$_SESSION['password'] = $password;
header("location: home.php");}
else {
echo "<p style='color:red;text-align:center;'>Wrong username or password!</p>";}
答案 0 :(得分:4)
在IF语句中将表单提交后应该执行的代码换行,以检查表单是否已提交:
if ('POST' === $_SERVER['REQUEST_METHOD'])
{
// your code goes here
}
答案 1 :(得分:3)
检查表单是否已提交
if(isset($_POST['user'])) {
//Your php code goes here
}
根据您的评论我延伸了这个答案
只需将所有代码置于您在问题中发送的条件
if(isset($_POST['user']))
{
//Get the form with POST
$user = mysql_real_escape_string($_POST['user']);
$password = mysql_real_escape_string($_POST['pass']);
$usernames=mysql_query("SELECT * FROM user_info WHERE Username='" . $_POST['user'] . "' AND Password='" . $_POST['pass'] . "'");
if(!$usernames){echo mysql_error();}
$count=mysql_num_rows($usernames);
if(!$count){echo mysql_error();}
//If $count is equal to one, register the user and redirect him to his page, or else echo him that his info is wrong
if($count === 1) {
$_SESSION['code'] = "titan";
$_SESSION['ande'] = $user;
$_SESSION['password'] = $password;
header("location: home.php");}
else {
echo "<p style='color:red;text-align:center;'>Wrong username or password!</p>";}
}
答案 2 :(得分:0)
我 DID NOT 告诉你的是PHP代码与表单和HTML的其余部分在同一个文件中...我试图用AJAX重新编写代码,(它没有' t work =(但它仍然有帮助!)为此我将PHP代码移到另一个文件(Login_engine.php
)中。就是这样!
当然,仍然存在一个小问题:现在,红色文本显示在Login_engine.php
内......太糟糕了!