Reputation: 21
Hey guys im having a little trouble with the PDO in php as the error it is returning is an undefined index. The code for the function and query and return of result is this:
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;
}
However when running the code for the index page i get an error that says Notice: Undefined index: name
The Code for the index is this:
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';
}
my question is why is it throwing a notice and how do i go around this problem?
Upvotes: 0
Views: 208
Reputation: 522015
fetchAll
returns all results (potentially multiple rows) in a multidimensional array:
array(
0 => array(/* first row */),
1 => array(/* second row */),
...
)
That's why the array doesn't have a direct index 'name'
, it needs to be [0]['name']
.
Or you shouldn't fetchAll
, just fetch
.
Upvotes: 2