問題描述
為什麼?我在控制枱中嘗試了相同的查詢,並返回了多行。這是查詢:
$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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。