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.

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!

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.

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

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;