查询数据库

时间:2017-05-29 17:37:01

标签: php jquery mysql ajax

我正在迈出PHP的第一步,现在我正在尝试创建一个简单的登录表单,并尝试通过查询数据库使用AJAX和PHP验证信息。 我使用Ajax是因为我需要更改页面上的一些元素,以防登录信息无效,之后我发现你实际上无法直接从jquery调用php函数,你需要使用ajax。 我在php文件中有这个表单:

  <body>
    <div class="wrapper" id="mainWrapper" style="display:none;">
      <img src="assets/icons/user.png" id="userLogo" alt="user-icon">
      <form>
      <div class="form-div">
        <input type="text" required id="username" name="user" placeholder="Username">
      </div>
      <div class="form-div">
        <input type="password" required id="password" name="pass" placeholder="Password">
      </div>
      <input type="button" name="submit" id="loginButton" value="login" onclick="post();" class="btn-login">
      </form>
      <br>
      <a href="recover.php">Forgot password?</a>
      <br>
      <div id="status"></div>
      </div>
    </div>
  </body>

我创建了这个ajax脚本,将我的变量发送到应该测试登录信息的php文件,这是ajax脚本:

    <script type="text/javascript">
      function post() {

   var hr = new XMLHttpRequest();
   // Create some variables we need to send to our PHP file
   var url = "testLogin.php";
   var username = document.getElementById("username").value;
   var password = document.getElementById("password").value;
   var vars = "username="+username+"&password="+password;
   hr.open("POST", url, true);
   // Set content type header information for sending url encoded variables in the request
   hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   // Access the onreadystatechange event for the XMLHttpRequest object
   hr.onreadystatechange = function() {
     if(hr.readyState == 4 && hr.status == 200) {
       var return_data = hr.responseText;

    if(return_data == "false")
    {
      document.getElementById('userLogo').style.display = "none";
      document.getElementById('userLogo').src = "assets/icons/error.png";
      $("#userLogo").fadeIn(1000);
      document.getElementById('status').innerHTML = "Username ou password inválidos";
    }
    else
    {
      document.getElementById('userLogo').style.display = "none";
      document.getElementById('userLogo').src = "assets/icons/user.png";
      document.getElementById('status').innerHTML = "";
      $("#userLogo").fadeIn(1000);
    }
     }
   }
   // Send the data to PHP now... and wait for response to update the status div
   hr.send(vars); // Actually execute the request
   document.getElementById("status").style.visibility = "a processar...";

      }
    </script>

我通过ID访问元素获取密码和用户名的值,然后将其发送到名为“testLogin.php”的php文件,其中包含用于测试登录信息的脚本 这是该文件的内容:

<?php
session_start();
include_once('connect.php');
if(isset($_POST['username']))
{
  $username = $_POST['username'];
  $password = $_POST['password'];
  $sql = "SELECT * FROM users WHERE Username = '".$username."' AND password ='".$password."' LIMIT 1";
  $result = mysql_query($sql) or die(mysql_error());
  if(mysql_num_rows($result) == 1)
  {
      $row = mysql_fetch_assoc($result);
      echo "true";
      exit();
  }
}
  else
  {
    echo "false";
    exit();
}
?>

我之前显示的ajax脚本我正在“监听”如果信息正确则回显为true,如果信息无效则回显为false。 当我将测试脚本中的代码更改为:

if($_POST['username'] == 'Joao' && $_POST['password'] == "meu")
echo "true";
else echo "false";

它工作得很好,因为我记得可能有一个错误,ajax调用php文件或与php查询数据库有关,我无法分辨,因为我觉得无力测试这个。 我很感激,如果有人能帮助我找出它是否与数据库的连接或者与ajax或php相关的东西。 谢谢

编辑:这是连接文件的内容

<?php
$host = "localhost";
$username = "root";
$password = "";
$db = "forum";
mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db($db);
 ?>
  

我现在已按照建议将所有已弃用的mysql函数更改为mysqli:

<?php
session_start();
include_once("config.php")
if(isset($_POST['username']) && isset($_POST['password']))
{

$status = "";
$username = $_POST['username'];
$password = $_POST['password'];
  if($bd = mysqli_connect('localhost','root','','forum'))
  {
     if($command = mysqli_prepare($bd,"SELECT *  FROM users WHERE Username = ? AND password = ? "))
     {
       mysqli_stmt_bind_param($command,"ss",$username,$password);
       mysqli_stmt_execute($command);
       mysqli_stmt_bind_result($command,$testUser,$testPass);
       mysqli_stmt_fetch($command);
       if($username == $testUser && $password == $testPass)
       $status = "true";
       else $status = "false";
       mysqli_stmt_close($command);
     }
    mysqli_close($bd);

  }

}
else $status = "false";

echo $status;
exit();

但我仍然得到相同的结果

2 个答案:

答案 0 :(得分:1)

经过数小时的研究和阅读文档以及所有这些,并且在您的问题的宝贵帮助下,我得到了实际工作的代码。 我已将ajax调用更改为:

<script>
 function confirmar()
 {
   var username = $("#username").val();
   var password = $("#password").val();
   $.ajax({
     //The file containing the script to test the login information
     url: "testLogin.php",
     //The type of the call (POST, GET)
     type: "POST",
     //the information to be tested, send it through the URL (form serialization may be a better choice than this aproach)
     data: "username="+username+"&password="+password
   }).done(function(resp)
   {
     //the server response stating that the test was a failure
     if(resp == "notok")
     {
       $('#loader').hide();
       $("#loginButton").show();
       $('#userLogo').css('display',"none");
       $('#userLogo').attr('src',"assets/icons/error.png");
       $("#userLogo").fadeIn(1000);
       $('#status').html("Username ou password inválidos");
       return;
     }
     else
     {
       $('#loader').show();
       $("#loginButton").show();
       $('#userLogo').css('display',"none");
       $('#userLogo').attr('src',"assets/icons/user.png");
       $('#status').html("");
       $("#userLogo").fadeIn(1000);
       window.location = "userDetails.php";
     }
   })
 }
  </script>
在我看来,这比我的可读性要强得多,而且我认为它也更容易理解。 在我理解了ajax调用实际上是如何工作之后,我去改变从数据库中获取数据的php文件并实际测试它:

<?php
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "" || $password == "")
{
  //server response if the info or the test wasnt valid
  echo "notok";
  exit();
}
}
else
{
  echo "notok";
  exit();
}
if($bd = mysqli_connect("localhost", "root", "", "forum"))
{
  if($stmt = mysqli_prepare($bd,
  "SELECT User_ID, username, password, email from users WHERE Username = '".$username."'")) {
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $idUser, $name, $pass, $email);
    mysqli_stmt_fetch($stmt);
    if($name == $username && $password == $pass) echo "ok";
    else echo "notok";
    mysqli_stmt_close($stmt);
  }
  mysqli_close($bd);
  }
 ?>

这实际上产生了我追求的结果。 我只有3个问题/问题atm。 第一个是在调用ajax的jquery函数中我认为这是测试用户名和密码字段是否为空的最佳位置。我已经通过添加以下代码行完成了这项工作:

   if(password == "" || username ||)
   {
     alert("please fill out the information required for the login");
     return;
   }

但在添加该代码后,ajax调用不再有效...... 第二件事是,我发现与ajax调用的表单序列化有关,我认为它比按元素ID获取值要熟练得多,我没有这个工作。

答案 1 :(得分:0)

使用jquery ajax调用可以简化大量代码。例如:

$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});

有关详细信息,请参阅jquery ajax手册,它非常简单。 在php脚本中:

  • 请在php中使用PDO代码安全。
  • 当您不想查看任何数据时,mysql_fetch_assoc()的需求是什么。
  • 此外,选择行只计算它们根本没有意义。必须运行count(*)查询,只返回一行。
  • if语句返回true,如果为false则返回false。所以还需要一个else语句。只有在未设置用户名时,您的其他人才会返回false。
  • 此外,session_start()在您的脚本中没有用处。

希望它能帮助你理解。

更新

问题1:如何验证表单?

解决方案:请参阅此示例:

    $(document).ready(function(){
     $('#form_id').on('submit',function(e){
        var username = $('#username').val();
        var password = $('#password').val();

       if(username == '' || password == '')
      {
      alert('required fields!!');
      e.preventDefault(); //stop submitting the form.
      }else{

     //here your ajax call

     }
   });

});

问题2:如何在表单提交中使用序列化?

解决方案:在jquery中这样做

   $('#form').serialize(); //use in your ajax call