Reputation: 124
What are the reason for these errors to be appearing?
Notice: Undefined index: photo
Notice: Undefined index: username
They are appearing inside the while loop, on '.$row['photo'].' and '.$row['username'].'
I'm just calling the public function on the PHP page as followed.
<?php echo $userSuggestions($uiD); ?>
The reason why I need it inside the while loop is that I'm trying to use PDO::FETCH_ASSOC so it does not repeat the same results when echoed.
I'm able to make it work with just $row = $sth->fetch()
then on the php page calling it as followed: $userSuggestions['photo'], $userSuggestions['Username']
but that way I won't be able to loop it and retrieve different results(different information instead of repeating same one over and over).
I've searched various threads to come to the conclusion that isset() is needed, but unable to understand why isset is needed inside this query, if anyone able to explain I'd appreciate it. Thank you.
public function userSuggestions($uiD)
{
$sth = $this->db->prepare("
SELECT F.friend_two AS possible_friend, U.username, U.uiD, U.photo
FROM user_friends F, users U
WHERE F.friend_one IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
AND F.friend_two NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
AND NOT F.friend_two = :uiD
AND U.uiD NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
AND U.photo NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
GROUP BY possible_friend
ORDER BY RAND()
");
$sth->execute(array(':uiD' => $uiD));
while($row = $sth->fetchAll(PDO::FETCH_ASSOC))
{
echo '
<div class="SuggestionsPhotoDiv">
<img src="'.$row['photo'].'" class="SuggestionsPhoto">
<span class="SuggestionsButton">
<a>Follow Me</a>
</span>
<span class="SuggestionsName">
<a>'.$row['username'].'</a>
</span>
</div>
'; return $row;
}
Upvotes: 1
Views: 1078
Reputation: 15538
Solution 1:
while($row = $sth->fetch(PDO::FETCH_ASSOC)){
// your current code here
}
This uses fetch
instead of fetchAll
. fetchAll
returns an array of all the results meaning that when you try to access $row['username']
it doesn't exist.
Solution 2:
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
// your current code here
}
This gets the output as an array of arrays then loops through them.
The fetchAll
function documentation: http://php.net/manual/en/pdostatement.fetchall.php
Here's your fetchAll
output:
array(2) {
[0]=> array(4) {
["possible_friend"]=> string(3)"154"
["username"]=> string(5) "Emily"
["uiD"]=> string(3) "151"
["photo"]=> string(96) "uploads/profilePictures/image2.jpg"
}
[1]=> array(4) {
["possible_friend"]=> string(3) "153"
["username"]=> string(5) "Emily"
["uiD"]=> string(3) "151"
["photo"]=> string(96) "uploads/profilePictures/image1.jpg"
}
}
You can see that it's outputting all results so the username
key doesn't exist in the top level array.
Upvotes: 3