无法从fetch_assoc()分配返回值

时间:2013-02-04 05:05:18

标签: php

我写了php

$query = "SELECT privilege , no, userName FROM  $tableName WHERE userName =   

'$inputAccount' and password = '$inputPassword'";

$result = $mysqli->query($query);

if($result){
       while ($row = $result->fetch_assoc()) {
        printf ("%s %s %s\n", $row["privilege"], $row["no"], $row["userName"]);
    }
}

结果为user 2 test

session_start();
$_SESSION["privilege"]=$row["privilege"];
$_SESSION["no"]=$row["no"];
$_SESSION["userName"]=$row["userName"]

echo $_SESSION["privilege"] ;
echo $_SESSION["no"];
echo $_SESSION["userName"];

但结果是没有任何东西,我已经修复了很长时间,但找不到原因?

提前谢谢。

2 个答案:

答案 0 :(得分:2)

使用下面的代码,问题是你没有将sql输出存储在变量中并在while循环之外访问结果。

session_start();
$query = "SELECT privilege , no, userName FROM  $tableName WHERE userName =   

'$inputAccount' and password = '$inputPassword'";

$result = $mysqli->query($query);

if($result){
       while ($row = $result->fetch_assoc()) {
        //printf ("%s %s %s\n", $row["privilege"], $row["no"], $row["userName"]);
       $pr = $row["privilege"];
       $no = $row["no"];
       $name = $row["userName"];
    }
}

$_SESSION["privilege"]=$pr;
$_SESSION["no"]=$no;
$_SESSION["userName"]=$name

echo $_SESSION["privilege"] ;
echo $_SESSION["no"];
echo $_SESSION["userName"];

答案 1 :(得分:1)

假设您在$_SESSION循环之后为while 分配值,$row将在该阶段false