1

我做了一个登录表单,我遇到了很多其他问题,现在我发现 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>";}
4

3 回答 3

5

将应该在表单提交后执行的代码包装在一个 IF 语句中,以检查表单是否已提交:

if ('POST' === $_SERVER['REQUEST_METHOD'])
{
    // your code goes here
}
于 2013-09-23T17:53:12.413 回答
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>";}

}
于 2013-09-23T17:54:05.847 回答
0

没有告诉你的是 PHP 代码与表单和 HTML 的其余部分在同一个文件中......我试图在 AJAX 中重新制作代码,(它不起作用=(,但它仍然有帮助! ) 并且为此我将 PHP 代码移到了另一个文件 ( Login_engine.php) 中。就是这样!当然,还有一个小问题:现在,红色文本显示在里面Login_engine.php......太糟糕了!

于 2013-09-25T15:55:56.273 回答