Skip to content
Advertisement

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement