PHP只选择第一行?

时间:2013-08-20 07:38:42

标签: php mysql

我有一个快速登录表单,我为学校做的唯一的问题是当我尝试登录一切工作完美时,我想登录到第一个用户(用户名:hbutler密码:密码)但是,当我尝试登录对于我的其他帐户,我得到页面刷新,如果它不正确,我已经设置了它是我的代码:

<?PHP

//Create the connection…
//("where the database is", 'Database login' , 'database password' , "Database name")
$con=mysqli_connect("", 'root', 'root', "Social");

//Check our connection…
if (mysqli_connect_errno($con))
{
    echo " Sorry Mate";
}
$username = $_POST['username'];
$password = $_POST['pawd'];
$result = mysqli_query($con, "SELECT * FROM User_info");
$row = mysqli_fetch_array($result);
$value = $row['username'];
if($value == "$username")
{
    $result = mysqli_query($con, "SELECT * FROM User_info WHERE username ='$username'");
    $row = mysqli_fetch_array($result);
    $value = $row['password'];
    if($value == "$password")
        {
        $sql=("UPDATE user_check SET user = '1', name = '$username'");
        header( 'Location: feed.php' ) ;
        }
        else
        {
        header( 'Location: social.php' ) ;
        }
}
else
{
header( 'Location: social.php' ) ;
}
if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
mysqli_close($con);
?>

哪个从前一页获取表单数据我不知道为什么会发生这种情况,我尝试将php更改为:

$result = mysqli_query($con, "SELECT username FROM User_info");
$row = mysqli_fetch_array($result);
if($row == "$username")

然而,这对任何建议都没有用?

2 个答案:

答案 0 :(得分:1)

问题是,在第一次查询之后,要从db获取信息,您只占用表的第一行,

$row = mysqli_fetch_array($result);

然后将其与提交的用户名进行比较,这就是您无法使用任何其他用户名登录的原因,解决方案是在第一个查询中添加WHERE子句,

$result = mysqli_query($con, "SELECT * FROM User_info WHERE username ='".$username."'");

然后比较更容易的密码,但仍然有更好的方法来进行身份验证。但是对于你的例子,这应该做。

答案 1 :(得分:0)

修改您的代码如下:

<?PHP

//Create the connection…
//("where the database is", 'Database login' , 'database password' , "Database name")
$con=mysqli_connect("", 'root', 'root', "Social");

//Check our connection…
if (mysqli_connect_errno($con))
{
    echo " Sorry Mate";
}
$username = $_POST['username'];
$password = $_POST['pawd'];

$result = mysqli_query($con, "SELECT count(*) as count FROM User_info WHERE username ='$username' and password='$password'");
while( $rows = mysqli_fetch_array($con, $result) )
{ //Check for SQL INJECTION
    if( $rows['count'] == 1 )
    {
        //$sql=("UPDATE user_check SET user = '1', name = '$username'");
        //header( 'Location: feed.php' ) ;
        //Other Operations
    }
    else
    {
        header( 'Location: social.php' ) ;
    }

}
mysqli_close($con);
?>