[英]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.我正在尝试获取
Wordpress
数据库中一列中的总数据 (SUM)。 I am using the following SQL (and PHP) code to run the request;我正在使用以下 SQL(和 PHP)代码来运行请求; 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)
;我试过使用
print_r($avg_items_purchased)
; and var_dump($avg_items_purchased)
;和
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.在 output 中,它打印了我正在寻找的数据,但我只想显示
items_purchased
的总和。
Is there a way I can simply output the variable, without the other data?有没有办法我可以简单地 output 变量,没有其他数据?
This is a job for$wpdb->get_var() .这是$wpdb->get_var()的工作。 You'll get a cleaner output from something like this:
你将从这样的东西中得到一个更干净的 output:
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这将是一个 HTML 段说
Sum of items purchased: 4.20
购买的物品总和:4.20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.