0

I'm generating an XML file using PHP for a website where they review tech products. In the XML file, I have to display the rating of products. For rating purposes, I'm using GD Star Rating plugin.

I've been experimenting with wpdb class to fetch the rating of each product. However I've not had any luck so far. I'm using the following SQL code on phpmyadmin and I'm able to to fetch the rating for any product review I want

SELECT review FROM tableName_gdsr_data_article WHERE post_id = 4627

But when I try this SQL code in PHP, as seen below, all I get is bunch of errors.

$post_id = $post->ID;
$reviewScore = $wpdb->query(
    $wpdb->prepare( 
    "SELECT review FROM tableName_gdsr_data_article WHERE post_id = '$post_id'"
    )
);

Does anyone have any idea why the code above doesn't work? Any help would be much appreciated.

Thanks in advance

1
  • Can you give an example of one or some of the errors? Commented Apr 20, 2012 at 12:55

2 Answers 2

1

You need to add the global $wpdb reference and also add the second parameter required for prepare():

global $wpdb;
$post_id = $post->ID;
$reviewScore = $wpdb->query(
    $wpdb->prepare( 
        "SELECT review FROM {$wpdb->prefix}gdsr_data_article WHERE post_id = %d",
        $post_id
    )
);
0

Oh, you'll kick yourself for this one.

You have:

$wpbd->prepare

Should be:

$wpdb->prepare

Simple typo :)

7
  • Ouch! that hurts :) Corrected the typo error but still getting an error. Here is error I get Fatal error: Call to a member function query() on a non-object in... The error points to the line $reviewScore = $wpdb->query Commented Apr 20, 2012 at 13:08
  • You need to call global $wpdb; somewhere above that query. Commented Apr 20, 2012 at 13:35
  • Adding global $wpdb;eliminated the fatal error. Thanks for that. But still the rating value is not returned. Instead it prints out the text Array in xml file. I guess the post ID is not properly passed into the query. Do you think that is the case? Thanks for the all help again. Commented Apr 20, 2012 at 13:57
  • Well the code you showed above assumes that you have the $post object, and therefore can get the post ID via $post->ID. But if you had to call $wpdb then you probably don't have the $post object and you can call it the same way (i.e. $global $wpdb, $post;). That will get the ID of the page/post you are currently on. Commented Apr 20, 2012 at 14:05
  • Unfortunately, that didn't solve the problem as well. But here is the full code I'm working on - pastebin.com/139mGqAw Maybe this will be of some help. Thanks again. Commented Apr 20, 2012 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.