Wordpress如何从get_results函数中获取值

时间:2017-04-27 10:56:50

标签: php mysql wordpress

我试图通过WordPress get_results函数从返回对象获取值,但是没有成功

示例代码

$myrows = $wpdb->get_results("SELECT SUM(view) as dviews FROM view_count WHERE post_id = '$pid'");

echo $myrows->dviews;   // echo nothing 

所以任何想法如何从中获取整数返回dviews

4 个答案:

答案 0 :(得分:1)

  

首先,如果您只想获得一条记录,请使用get_row()   代替get_results(),因为它将获取所有检索到的数据   通过SQL查询。

单曲

$result = $wpdb->get_row("SELECT SUM(view) as dviews FROM view_count WHERE post_id = '$pid'");
echo $result->dviews;

对于多个记录

$results = $wpdb->get_results("SELECT SUM(view) as dviews FROM view_count WHERE post_id = '$pid'");
foreach ($results as $result)
{
    echo $result->dviews;
}

请注意:如果您有表格前缀,请使用$wpdb->prefix获取正确的表名。

希望这有帮助!

答案 1 :(得分:0)

尝试这样的事情,

foreach( $wpdb->get_results("SELECT SUM(view) as dviews FROM view_count WHERE post_id = '".$pid."';") as $key => $row) {
    // each column in your row will be accessible like this
        echo $row->column_name;
    }

它应该有用。

答案 2 :(得分:0)

试试这个

$myrows = $wpdb->get_results("SELECT SUM(view) as dviews FROM view_count WHERE post_id =".$pid."");
foreach($myrows as $item)
{
echo $item->dviews;
}

答案 3 :(得分:0)

请添加表的前缀,并在查询中将$ wpdb声明为全局变量。我已将您的查询修改为:

global $wpdb;
$myrows = $wpdb->get_results("SELECT SUM(view) as {prefix}dviews FROM view_count WHERE post_id = '$pid'");

echo $myrows[0]->dviews;