'Display SQL query result on front-end Wordpress site
I am trying to get the total data (SUM) within a column in a Wordpress database. I am using the following SQL (and PHP) code to run the request; however, I do not know how to display the result on the front end of my site.
global $wpdb;
$avg_items_purchased = $wpdb->get_results('SELECT SUM(items_purchased) FROM cogs');
print_r($avg_items_purchased);
or
var_dump($avg_items_purchased);
I have tried using print_r($avg_items_purchased); and var_dump($avg_items_purchased); but it outputs more information than I would like. Within the output, it prints the data that I am looking for, but I would like only the SUM of items_purchased to be displayed.
Is there a way I can simply output the variable, without the other data?
Solution 1:[1]
This is a job for $wpdb->get_var(). You'll get a cleaner output from something like this:
global $wpdb;
$avg_items_purchased = $wpdb->get_var('SELECT SUM(items_purchased) FROM cogs');
?><p>Sum of items purchased: <?=$avg_items_purchased?></p><php?
It will be an HTML paragraph saying
Sum of items purchased: 4.20
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | O. Jones |
