How can I use a variable in PHP $row-> from a db table?
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 f开发者_JS百科ields):
$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.
Why not fetch an array with pg_fetch_assoc instead of an object so you can just do;
$myfield=$row[$field];
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>
}
}
精彩评论