問題描述
為什麼?我在控制檯中嘗試了相同的查詢,並返回了多行。這是查詢:
$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:要檢索整個錶行,您可以使用它。
例:
<?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);
?>
透過在 get_row 中使用 ARRAY_A 引數,您的帖子資料作為關聯陣列返回。或者,您可以使用 ARRAY_N 引數以數字索引的陣列返回您的帖子資料。
3. $wpdb->get_results:標準 SELECT 查詢應使用 get_results 函式從資料庫中檢索多行資料。
<?php
$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>';
}
?>
你需要最後一個,你可以期待。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。