如何在$wpdb中获取数组?

时间:2016-05-04 作者:saphus

我有一个从数据库表中选择数据的代码段。但我遇到了一个错误:Warning: Invalid argument supplied for foreach()

我遇到一个新错误:Notice: Trying to get property of non-object在此行中echo $result->Name;

代码段(已更新):

$results = $wpdb->get_results( \'SELECT DATE_FORMAT(FROM_UNIXTIME(submit_time), "%b %e, %Y  %l:%i %p") AS Submitted,
                    MAX(IF(field_name="Name", field_value, NULL )) AS "Name",
                    MAX(IF(field_name="Email", field_value, NULL )) AS "Email",
                    MAX(IF(field_name="Subject", field_value, NULL )) AS "Position",
                    MAX(IF(field_name="Message", field_value, NULL )) AS "Message"
                    FROM tablename
                    WHERE form_name = "Resume"
                    GROUP BY submit_time
                    ORDER BY submit_time DESC\', ARRAY_A);

foreach($results as $result){
    echo $result->Name;
}

Link

3 个回复
最合适的回答,由SO网友:Ahed Eid 整理而成

您的查询有问题,无法使用GROUP BYORDER BY 之前WHERE

代替

FROM tablename GROUP BY submit_time ORDER BY submit_time DESC
使用

FROM tablename
这是您的查询

$results = $wpdb->get_results( \'SELECT DATE_FORMAT(FROM_UNIXTIME(submit_time), "%b %e, %Y  %l:%i %p") AS Submitted,
            MAX(IF(field_name="Name", field_value, NULL )) AS "Name",
            MAX(IF(field_name="Email", field_value, NULL )) AS "Email",
            MAX(IF(field_name="Subject", field_value, NULL )) AS "Position",
            MAX(IF(field_name="Message", field_value, NULL )) AS "Message"
            FROM tablename
            WHERE
            form_name = "Resume"
            GROUP BY submit_time
            ORDER BY submit_time DESC\', ARRAY_A);

SO网友:Jamie

我要大刀阔斧,但是ARRAY_A 将返回关联数组

然后,您将尝试作为对象访问此关联数组

简单更改:

foreach($results as $result){
    echo $result->Name;
}
收件人:

foreach($results as $result){
    echo $result[\'Name\'];
}
错误应该消失!

SO网友:Swopnil Dangol

$wpdb->get_results 返回多维数组。因此,foreach的论点应该是:

foreach($results as $object=>$result){
    echo $result->Name;
}
始终在访问对象和数组之前转储它们。