donglian4464
2017-04-27 10:56
浏览 74
已采纳

Wordpress如何从get_results函数中获取值

I'm trying to get value from return object by WordPress get_results function but no success with it

Sample code

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

echo $myrows->dviews;   // echo nothing 

so any idea how to get the integer return as dviews from it.

图片转代码服务由CSDN问答提供 功能建议

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

示例代码

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

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • duancan65665 2017-04-27 12:02
    已采纳

    First of all if you want to get only one record then use get_row() instead of get_results() because it will fetch all the data retrieved by SQL query.

    For single record

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

    For multiple records

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

    Please Note: If you have a table prefix the use $wpdb->prefix to get the correct table name.

    Hope this helps!

    打赏 评论
  • dongse5528 2017-04-27 11:38

    Try something like this,

    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;
        }
    

    It should work.

    打赏 评论
  • doubi9999 2017-04-27 11:46

    Try this

    $myrows = $wpdb->get_results("SELECT SUM(view) as dviews FROM view_count WHERE post_id =".$pid."");
    foreach($myrows as $item)
    {
    echo $item->dviews;
    }
    
    打赏 评论
  • doubu0897 2017-04-27 12:00

    Kindly add the prefix of your table and declare $wpdb as global variable as well in your query. I have modified your query as :

    global $wpdb;
    $myrows = $wpdb->get_results("SELECT SUM(view) as {prefix}dviews FROM view_count WHERE post_id = '$pid'");
    
    echo $myrows[0]->dviews;
    
    打赏 评论

相关推荐 更多相似问题