为什么会这样?我在控制台中尝试了相同的查询,它返回了多行。以下是查询:
$this->wpdb->get_row("SELECT * FROM ".$this->wpdb->users." WHERE status = \'active\'", ARRAY_A);
为什么会这样?我在控制台中尝试了相同的查询,它返回了多行。以下是查询:
$this->wpdb->get_row("SELECT * FROM ".$this->wpdb->users." WHERE status = \'active\'", ARRAY_A);
实际上,使用get_row()
只有当您希望得到一个结果时,否则您可以使用get_results()
有三种方法可以从数据库中提取数据。
1.$wpdb->get_var
:使用此选项可以从数据库表中获取单个值。比如,如果你想计算评论的总数。您可以通过以下方式进行操作:
<?php
$comment_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments;"));
echo \'<p>Total comments: \' . $comment_count . \'</p>\';
?>
2。$wpdb->get_row
: 要检索整个表行,可以使用此选项。Example:
<?php
$thepost = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = 1" ) );
echo $thepost->post_title;
?>
或<?php
$thepost = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = 1" ), ARRAY_A );
print_r ($thepost);
?>
通过使用ARRAY_A
get\\u行中的参数您的post数据将作为关联数组返回。或者,您可以使用ARRAY_N
参数返回数字索引数组中的post数据。3.$wpdb->get_results
:标准SELECT
查询应使用get\\u results函数从数据库中检索多行数据。
<?php
global $wpdb;
$allposts = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_title FROM $wpdb->posts WHERE post_status = \'publish\'") );
foreach ($allposts as $singlepost) {
echo \'<p>\' .$singlepost->post_title. \'</p>\';
}
?>
and you need the last one, as you can expect.
$wpdb->get_row(\'query\', output_type, row_offset);
row\\u offset(integer)所需行(0为第一行)。默认值为0。我的解决方案很简单。。
<?php
function count_results() {
# use the data base
global $wpdb;
# Query to count all results from one table
$sql_count_results = \'
SELECT count(*) as count
FROM `YOUR_TABLE`;\';
# Ejecute function
$results = $wpdb->get_row( $sql_count_results , OBJECT );
# Return results
return $results->count;
}
使用:<?php
echo count_results();
是否有一种简单的方法可以对来自$wpdb->get\\u results()的结果集分页?我想在author\\u archive页面上获得用户评论的分页列表-社区中的一些用户的评论超过500条,因此分页很重要。WordPress有没有内置的方法来实现这一点,或者我需要自己构建它?[更新以添加代码]<!-- Show comments --> <?php $querystr = \" SELECT comment_ID, comment_post_