2017-05-27 63 views
0

我是PHP初学者。 我的代码在php错误中更改innerHTML

<?php 
    session_start(); 
    $username = "ADMIN"; 
    $host = "localhost"; 
    $password = "chmuhammadsohaib123"; 
    $database = "USER"; 
    $con = mysqli_connect($host, $username, $password, $database); 
    $USERNAME = $_POST["lusername"]; 
    $PASSWORD = $_POST["lpassword"]; 
    if (isset($_POST["login"])) { 
     if (isset($_POST["loggedin"])) { 
       setcookie("RAUSERNAME", $USERNAME); 
       setcookie("RAPASSWORD", $PASSWORD); 
      } 
     $_SESSION["SRAUSERNAME"] = $USERNAME; 
     $_SESSION["SRAPASSWORD"] = $PASSWORD; 
    } 
    if (isset($_POST["login"])) { 
     $data = mysqli_query($con, "SELECT * FROM `INFO` WHERE `USERNAME` = '$USERNAME'"); 
     if (mysqli_num_rows($data)>0) { 
      echo "<script type='text/javascript'>window.location.replace('../');</script>"; 
     } 
     else { 
      print("<script type='text/javascript'>document.getElementsByClassName('errors').innerHTML = '<h1 class='redback'>SORRY, BUT THIS ACCOUNT DOESN'T EXISTS</h1>';</script>"); 
     } 
    } 
?> 

我的HTML页面

<body> 
    <div class="errors"></div> 
     <fieldset class="replacement"> 
      <legend>LOGIN</legend> 
      <h1>LOGIN WITH YOUR INFORMATION</h1><br><br> 
      <form method="POST" action="<?php $_SERVER["php_self"]; ?>"> 
      <input type="text" name="lusername" placeholder="YOUR USERNAME"> 
<input type="password" name="lpassword" placeholder="YOUR PASSWORD" class="password"> 
<br> 
<br> 
<label>KEEP ME LOGGED IN: </label> 
<input type="checkbox" name="loggedin" checked> 
<br><br> 
<input type="submit" name="login" value="LOGIN"></form> 
     </fieldset> 
    </div> 
</body> 
</html> 

如上所述当我改变错误的innerHTML,它不会改变。它说;中缺少控制台或有时是错误。我该如何解决它?

+0

怎样的PHP涉及到HTML网页? – chris85

+1

你对SQL注入开放,并有错误的登录逻辑,你需要检查密码(应该被哈希)。 – chris85

+0

通过在php中请求 –

回答

2

在您回应您的JavaScript代码的点上,id为errors的html元素不存在于dom中。所以getElementById的回报将永远不确定。

<script>document.getElementById("errors")...</script> 
... some more html 
<div id="errors"></div> 

您可以通过调用JavaScript代码后的DOM文档准备解决这个问题。使用jQuery,你可以做这这样

// event handler for document ready 
$(function() { 
    // at this point, the dom is ready and the 'errors' id exists 
    $('#errors').html("some error message"); 
}); 

这工作,但似乎有点多余。更好的方法是用php回显实际的错误信息,并且不要使用javascript来执行此操作。

$error = false; 
if (mysqli_num_rows($data)>0) { 
    header('location: ../'); 
} else { 
    $error = '<h1 class="redback">SORRY, BUT THIS ACCOUNT DOESN\'T EXISTS</h1>'; 
} 

后来

<div class="errors"> 
<?php if ($error) echo $error; ?> 
</div> 
+0

谢谢,菲利普 –

+0

菲利普真的很好回答。 –