Home > Back-end >  Accessing mySQL columns dynamically using PHP
Accessing mySQL columns dynamically using PHP

Time:11-15

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.

CodePudding user response:

You are so near, just replace "theProp" in $row["theProp"] with $prop.

So this should work:

$prop = "theProp";

$test3 = $row[$prop];

In your case, $row is an array, not an object, that's why $row->$prop doesn't work.

CodePudding user response:

Just try casting the array as an object. The below works fine:

$array['one'] = "number 1, ";
$array['two'] = "number 2, ";

$object = (object) $array;

echo $object->one;
echo $object->two;



Output: number 1, number 2, 

CodePudding user response:

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.

  • Related