$ _SESSION变量在设置时始终显示“ S”而不是预期变量

时间:2019-04-18 10:25:41

标签: php authentication mysqli

<?php
if($_POST)
{
include 'config.php';
$referencenumber=$_POST['reference_number'];
$fullname=$_POST['full_name'];
$sRef=mysqli_real_escape_string($conn,$referencenumber);
$sName=mysqli_real_escape_string($conn,$fullname);
$query="SELECT * From customers where reference_number='$sRef' and 
full_name='$sName'";
$result=mysqli_query($conn,$query);
if(mysqli_num_rows($result)==1)
{
    session_start();
    $_SESSION['id'] = $query['id'];
    $_SESSION['refnumber'] = $query['reference_number'];
    header('location:index.php');
}
}

?>

上面的代码是我在login.php页面上写的。成功登录后,用户将到达index.php页面。

var lz_data = {overwrite:true,111:'<?php 
print_r($_SESSION['refnumber'])?>',

然后,我尝试在此处的下一页上打印参考号,这将设置一个与$ _SESSION ['refnumber']中的参考值匹配的值,但是由于某种原因,此代码的输出似乎始终为'S '在打印时,只有字母S。当我尝试打印$ _SESSION ['id']时,也会得到相同的输出。有什么想法吗?

编辑:session_start();已在index.php的开头添加,并且双引号不能解决问题。

1 个答案:

答案 0 :(得分:1)

您尝试获取字符串的特定索引,而不是结果/行数组:

$query="SELECT * From customers where reference_number='$sRef' and full_name='$sName'";
$_SESSION['id'] = $query['id']; // $query is a string not an array.
$_SESSION['refnumber'] = $query['reference_number']; // $query is a string not an array.

为什么在会话中只获得“ S”?

您可以在PHP上像数组一样使用字符串值。因此,您可以使用$query[0]获取“ S”,并使用$query[1]获取“ E”,依此类推。在您的情况下,$query['id']$query[0]相同,因为var_dump('id' == 0)为真。

demo on ideone.com

如何解决此问题?

您可以使用mysqli_result::fetch_array方法从$result获取具有列作为索引的行:

//get the $row from $result with fetch_array.
$row = $result->fetch_array(MYSQLI_ASSOC);

//now you can use the row array to set the values to the session.
$_SESSION['id'] = $row['id'];
$_SESSION['refnumber'] = $row['reference_number'];

因此您的代码如下所示:

<?php
if($_POST) {
    include 'config.php';

    $referencenumber = $_POST['reference_number'];
    $fullname = $_POST['full_name'];

    $sRef = mysqli_real_escape_string($conn, $referencenumber);
    $sName = mysqli_real_escape_string($conn, $fullname);

    $query = "SELECT * From customers where reference_number='$sRef' and full_name='$sName'";
    $result=mysqli_query($conn, $query);

    if(mysqli_num_rows($result) == 1) {

        //get the $row from $result with fetch_array.
        $row = $result->fetch_array(MYSQLI_ASSOC);

        session_start();
        $_SESSION['id'] = $row['id'];
        $_SESSION['refnumber'] = $row['reference_number'];
        header('location:index.php');
    }
}