1

I am trying to create a login script with PHP. Users are redirected to it by a login form with username and password fields. My problem here is that mysqli fetch_assoc() does not return anything. I tried the same query on the database and it works as expected. I tried using fetch_array with mysql_assoc, or as numeric array but still no luck. I tried accessing with both $row[0] and $row[password] for the returned value, but when running I get the "no rows found, nothing to print", so I guess everything works good until that point.

Any hints as to what I might be missing?

<?php 
$con=mysqli_connect('localhost','root','','site');

if(!$con)
{
die('Could not connect to database : ' . mysql.error());
}

$result=mysqli_query($con,'SELECT Password FROM users WHERE Username="$_POST[iusrname]" LIMIT 1');

if (!$result)
{
    Die("Could not successfully run query from DB: " . mysql_error());
}

$row = mysqli_fetch_assoc($result);

if (mysqli_num_rows($result) == 0)
{
    die("No rows found, nothing to print");
}


if($_POST[ipwd] == '$row[password]')
{
echo "Authentication succeeded.You will be redirected to the main page shortly";
$_SESSION['loged']=true;
$_SESSION['user']=$_POST[iusrname];
}
else
{
die("could not authenticate user");
}

mysqli_close($con);
?>
4

2 回答 2

2

我发现了错误,我想。

在单引号 ( '') 中,PHP 不会自动将变量名替换为变量值。使用双引号应该可以解决问题:

$username = mysqli_real_escape_string($con, $_POST['iusrname']); // For @cHao
$result=mysqli_query($con,"SELECT Password FROM users WHERE Username='$username' LIMIT 1");
于 2013-05-27T19:10:22.567 回答
1

尝试从这里更改您的查询:

'SELECT Password FROM users WHERE Username="$_POST[iusrname]" LIMIT 1'

对此:

'SELECT Password FROM users WHERE Username='.$_POST['iusrname'].' LIMIT 1'

你也会在这里遇到问题:

if($_POST[ipwd] == '$row[password]')

应该:

if($_POST["ipwd"] == $row["password"])

最有可能在这里:

$_SESSION['user']=$_POST[iusrname];

那应该是:

$_SESSION['user']=$_POST['iusrname'];
于 2013-05-27T19:09:43.673 回答