登录PhP脚本


Login PhP Script

所以我一直试图得到我的验证脚本为我的登录工作。

这里是代码:

  <?php
   ob_start();
   $host="localhost"; // Host name 
   $username="***"; // Mysql username 
   $password="***"; // Mysql password 
   $db_name="**"; // Database name 
   $tbl_name="**"; // Table name 
    // Connect to server and select databse.
   mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
   mysql_select_db("$db_name")or die("cannot select DB");
   // Define $myusername and $mypassword 
   $myusername=$_POST['username']; 
   $mypassword=$_POST['password']; 
   // To protect MySQL injection (more detail about MySQL injection)
   $myusername = stripslashes($myusername);
   $mypassword = stripslashes($mypassword);
   $myusername = mysql_real_escape_string($myusername);
   $mypassword = mysql_real_escape_string($mypassword);
   $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and     password='$mypassword'";
   $result=mysql_query($sql);
   // Mysql_num_row is counting table row
   $count=mysql_num_rows($result);
   // If result matched $myusername and $mypassword, table row must be 1 row
   if($count==1){
   // Register $myusername, $mypassword and redirect to file "login_success.php"
      session_register("myusername");
      session_register("mypassword"); 
      echo "Welcome $myusername";
      header("location:../htdocs/home.php");
      exit();
   }
   else {
      echo "Wrong Username or Password";
   }
   ob_end_flush();
?>

什么是奇怪的是,如果我输入凭据不在我的数据库它确实返回,他们是不正确的。但如果正确就不会重定向到home。php

这个代码非常糟糕,建议你不要使用它。至于问题,您使用的SQL函数是错误的。

replace $result=mysql_query($sql); with $result=mysql_fetch_array($sql);

if($count==1){变为if($result){

这应该解决您的问题,也在SQL语句的末尾添加LIMIT 1