2017-05-27 48 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

菲利普真的很好回答。 –