PDO:fetchAll分配数组变量

时间:2016-08-09 04:03:37

标签: php mysql pdo

我一直在用这一小段代码进行大约2个小时的战斗,用它研究并试图弄清楚我哪里出错了。经过9个小时的编码,我遇到了这个小问题,现在我处于深水状态。此时我有一个3800行代码依赖于它并且它在水中死了。

问题是没有任何最终变量会返回任何信息,它们将完全返回空白/空。当我尝试用“$ getranks ['nickname']”分配“myname”时,它甚至都没有做任何事情,即使我的“print_r($ getranks)”还带有所有这些信息。我也试过fetch而不是fetchAll,但后来我只得到一个结果。

我带了一个旧的MYSQL网站,我在互联网上为一组受到SQL注入的网站,所以我完全使用PDO重新制作它。这就是我遇到的问题。

非常感谢任何帮助。我很头疼,在等待援助的时候我会去吃晚餐。谢谢大家。

代码:“index.php”

$myid = $_SESSION['user'];

echo "User Session ID #" . $myid . ".<br><br>";

if(!empty($_SESSION['user'])) {
    $checkrank = $db->prepare("SELECT * FROM logins WHERE id = :myid");
    $checkrank->bindParam(':myid',$_SESSION['user']);
    $checkrank->execute();

    $getranks = $checkrank->fetchAll(PDO::FETCH_CLASS);

        print_r($getranks);
        $myname = $getranks['nickname'];
        $mycallsign = $getranks['callsign'];
        $mystatus = $getranks['status'];
        $mycallnum = $getranks['callnumber'];
        $myrank = $getranks['rank'];
        $mynote = $getranks['note'];
        $mybadge = $getranks['mybadge'];

    echo "<br><br>Check rank passed, the query came back with information.<br/>";
    echo "The session ID used to retrieve this information in the query was: " . $myid;
    echo "<br> Your name is " . $myname . ".";
}

结果:

    User Session ID #0102.

Array ( [0] => stdClass Object ( [id] => 0102 [badge] => 201 [rank] => 6 [nickname] => Rodger Anderson [username] => MASKED [password] => MASKED [salt] => MASKED [email] => MASKED [note] => [callsign] => [profile] => http://www.MASKED.net/forums/member.php?MASKED [callnumber] => [status] => ) ) 

Check rank passed, the query came back with information.
The session ID used to retrieve this information in the query was: 0102
Your name is .

You are SESSION[0102]
Your name is [] and your badge number is #.

旧代码:

$myid = $_SESSION['user'];

    echo "User Session ID #" . $myid . ".<br><br>";

    if(!empty($_SESSION['user'])) {
        $query = mysql_query("SELECT * FROM logins WHERE id = $myid");
        $getranks = mysql_fetch_assoc($query);

        $myname = $getranks['nickname'];
        $mycallsign = $getranks['callsign'];
        $mystatus = $getranks['status'];
        $mycallnum = $getranks['callnumber'];
        $myrank = $getranks['rank'];
        $mynote = $getranks['note'];
        $mybadge = $getranks['mybadge'];

        echo "<br><br>Check rank passed, the query came back with information.<br/>";
        echo "The session ID used to retrieve this information in the query was: " . $myid;
        echo "<br> Your name is " . $myname . ".";
    }

1 个答案:

答案 0 :(得分:0)

$getranks是一个对象数组,而不是关联数组。查看print_r($getranks)

的结果

你应该做类似

的事情

$myname = $getranks[0]['nickname'];

或者使用PDO::FETCH_ASSOC,但即使这样你也需要[0]。