如何在db表中使用PHP $ row->中的变量?

I have several fields in a PostgreSQL db table which I want to access in a PHP loop, since I want the same things to happen to each of them.

They are named similarly (3 lowercase letters), eg "mor", "gls", etc, and the various names are stored in an array called $fields.

The core of the code I'm using is as follows (I'm retrieving each row from the table, and then trying to loop through the fields):

$sql="select * from mytable order by id";
$result=pg_query($db_handle,$sql);
while ($row=pg_fetch_object($result))
{
  foreach ($fields as $field)
  {
    $myfield=$row->$field;
    <do something with $myfield>
  }
}

Unfortunately, the $row->$field doesn't work. I get the following:

PHP Notice:  Undefined property: stdClass::$mor
PHP Notice:  Undefined property: stdClass::$gls

I've tried various permutations of brackets and quotes, but I can't seem to find the magic dust. Is this doable?

Thanks.

var_dump( $row );

and check if $row is what you expect.

Try $myfield=$row->{$field}

You should iterate through the row, it will give you the column names (key) and their values (value)

you cant iterate through $fields, as it does not exist.

$sql="select * from mytable order by id";
$result=pg_query($db_handle,$sql);
while ($row=pg_fetch_object($result))
{
  foreach ($row as $key => $value)
  {
    $myfield=$value;
    <do something with $myfield>
  }
}

Why not fetch an array with pg_fetch_assoc instead of an object so you can just do;

$myfield=$row[$field];