Home > Mobile >  Display SQL query result on front-end Wordpress site
Display SQL query result on front-end Wordpress site

Time:03-12

I am trying to total (SUM) the data 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?

Thank you for your help.

CodePudding user response:

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

  • Related