繁体   English   中英

从数据库中检索值

[英]Retrieve value from database

我正在尝试使用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);
?>

我想,我发现了这个错误。

在单引号( '' )中,PHP不会自动用变量值替换变量名。 使用双引号应该可以做到这一点:

$username = mysqli_real_escape_string($con, $_POST['iusrname']); // For @cHao
$result=mysqli_query($con,"SELECT Password FROM users WHERE Username='$username' LIMIT 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'];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM