WordPress and PHP tips

Debug

echo '<pre>';
print_r($points_sum);
echo '</pre>';
var_dump($wpdb->last_query);

Three ways to pull data from the database.

https://wordpress.stackexchange.com/questions/14239/wpdb-get-row-only-returns-a-single-row

1.$wpdb->get_var:use this to get a single value from the database table. Like if you want to count the total number of comments. You can do it in following way:

<?php 
$comment_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments;")); 
echo '<p>Total comments: ' . $comment_count . '</p>';
?>

2.$wpdb->get_row : To retrieve an entire table row you can use this.

Example:

<?php 
$thepost = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = 1" ) );
echo $thepost->post_title; 
?>

OR

<?php 
$thepost = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = 1" ), ARRAY_A );
print_r ($thepost); 
?>

By using the ARRAY_A parameter in get_row your post data is returned as an associative array. Alternatively, you could use the ARRAY_N parameter to return your post data in a numerically indexed array.

3.$wpdb->get_results:Standard SELECT queries should use the get_results function for retrieving multiple rows of data from the database.

<?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>';
}
?>

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart
TOC
Scroll to Top