PHP数据库PDO连接

时间:2013-05-20 09:30:50

标签: php database pdo

嘿伙计我在php中的PDO有点麻烦,因为它返回的错误是一个未定义的索引。函数和查询以及结果返回的代码是:

function getUserDetails($user) {
   $db = connect();
try {
    $stmt = $db->prepare('SELECT name,addr AS address,team
FROM TreasureHunt.Player LEFT OUTER JOIN TreasureHunt.MemberOf ON (name=player) 
LEFT OUTER JOIN TreasureHunt.PlayerStats USING (player)
WHERE name=:user');

    $stmt->bindValue(':user', $user, PDO::PARAM_STR);

    $stmt->execute();
    $results = $stmt->fetchAll();
    $stmt->closeCursor();

} catch (PDOException $e) { 
    print "Error : " . $e->getMessage(); 
    die();
}
return $results;  
}

然而,当运行索引页面的代码时,我收到一条错误,上面写着通知:未定义索引:名称

索引的代码是:

try {
$details = getUserDetails($_SESSION['player']);
echo '<h2>Name</h2> ',$details['name'];
echo '<h2>Address</h2>',$details['address'];
echo '<h2>Current team</h2>',$details['team'];
echo '<h2>Hunts played</h2> ',$details['nhunts'];
echo '<h2>Badges</h2>';
foreach($details['badges'] as $badge) {
    echo '<span class="badge" title="',$badge['desc'],'">',$badge['name'],'</span><br />';
}
} catch (Exception $e) {
echo 'Cannot get user details';
}

我的问题是为什么要发出通知,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

fetchAll多维数组中返回所有结果(可能是多行):

array(
    0 => array(/* first row */),
    1 => array(/* second row */),
    ...
)

这就是为什么数组没有直接索引'name',它必须是[0]['name']
或者你不应该fetchAll,而只是fetch