[英]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. 我想在PHP循环中访问PostgreSQL数据库表中的几个字段,因为我希望每个字段都发生相同的事情。
They are named similarly (3 lowercase letters), eg "mor", "gls", etc, and the various names are stored in an array called $fields. 它们的名称类似(3个小写字母),例如“ mor”,“ gls”等,各种名称存储在称为$ 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. 不幸的是,$ row-> $ field不起作用。 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. 谢谢。
为什么不使用pg_fetch_assoc而不是对象来获取数组,所以您可以这样做;
$myfield=$row[$field];
var_dump( $row );
并检查$row
是否符合您的期望。
试试$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. 您无法遍历$ fields,因为它不存在。
$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>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.