从数据库中检索值

时间:2013-05-27 19:04:31

标签: php mysql

我正在尝试使用PHP创建登录脚本。用户通过包含用户名和密码字段的登录表单重定向到该用户。我的问题是mysqli fetch_assoc()没有返回任何内容。我在数据库上尝试了相同的查询,它按预期工作。我尝试将fetch_array与mysql_assoc一起使用,或者作为数字数组但仍然没有运气。我尝试使用$row[0]$row[password]访问返回的值,但是在运行时我得到“没有找到行,没有要打印”,所以我想在此之前一切正常。

关于我可能遗失的任何提示?

<?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);
?>

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分: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'];
相关问题