r/PHPhelp • u/Theo468 • Nov 01 '25
Solved Undefined Array Key - Send Help!
Hello,
Looking for some assistance. I am currently doing a course on PHP and inputting data from a database but I'm getting an error "Undefined array key"
Can someone help me and tell me what I've missed?
The code was copy and pasted direct from what the lecturer gave us.
I'd ask my lecturer but with it being the weekend they are unavailable until Monday and this is annoying me.
Thanks
3
Upvotes
5
u/juu073 Nov 01 '25
It means there is no column for either artist, album, or weeks (or any combination of these three columns) in the database, and thus the keys (those three items) don't exist in the array $row when you loop through and display them.
Do a print_r($row) inside the loop to test and see what is coming out.
3
u/allen_jb Nov 01 '25
(Ignore this comment because it'll probably just confuse you and it's not really related to your problem. I just have a thing about lies (of omission) in teaching)
This is ... not the whole truth.
foreachhandles not only arrays and Traversable objects, of which PDOStatement is one (via IteratorAggregate), but also non-Traversable objects.This line is actually completely unnecessary. You can just write:
Crazy mad opinion: If you really want to learn "how foreach works under the hood" in terms of "the array pointer", implement your own Iterator