I pull a row out of the database and I want to access it via a dynamic var
$prop = "theProp";
$test0 = $row["theProp"]; // Works fine
$test1 = $row->{$prop}; // Doesn't work
$test2 = $row->$prop; // Doesn't work
I’ve looked all over the place, obviously doing something stupid, can someone enlighten me please.
3
Answers
You are so near, just replace
"theProp"
in$row["theProp"]
with$prop
.So this should work:
In your case,
$row
is an array, not an object, that’s why$row->$prop
doesn’t work.Just try casting the array as an object. The below works fine:
Alternatively you can use
fetch_object()
/mysqli_fetch_object()
when you pull data from the database. Your$row
is an array and not an object, which is why your code doesn’t work.