mn8809
mn8809

Reputation: 452

Display Specific Image Based On SQL Query Result

I have a page that displays products based on a previous user query. The search results contain sets of metadata, most importantly a "product rating" on a 1-10 scale.

Here's the code that pulls the product rating metadata

<?php echo get_post_meta( get_the_ID(), 'product_rating', true ); ?>

This pulls the 'rating' metadata from our dB and simply displays the rating as a numeral (1, 1.5, 2, 2.5 ect).

I'm looking to take the value of the 'product_rating' and set an image to display for each value. A rating of 1 will display one image, while a rating of 2 display a different image ect ect.

The current code I have in place substitutes an image for the value, but the image is displaying multiple times (up to 10 times for a single value). My code is below, using a rating value of "4" as an example.

<?php $rating = get_post_meta( get_the_ID(), 'product_rating', true ); ?>

<?php For($i=4; $i <= $rating; $i++){
echo "<img src='http://www.domain.com/lpimage/lock50.png' />";
}
?>

Is my code close to where I need to be, or am I completely off base for the function I want?

Upvotes: 0

Views: 1022

Answers (1)

Brian DeMilia
Brian DeMilia

Reputation: 13248

Assuming your rating variable is correctly defined I think you can handle the conditional display of various images as follows:

<?php if ($rating == 1) echo '<img src="urlofimage1.jpg"></img>';
  elseif ($rating == 2) echo '<img src="urlofimage2.jpg"></img>';
  elseif ($rating == 3) echo '<img src="urlofimage3.jpg"></img>';
  elseif ($rating == 4) echo '<img src="urlofimage4.jpg"></img>';
?>

You use the double equal sign when comparing a value, you only use the single equal sign (=) when setting a variable's value.

Use >= and <= for ranges, ie. 1.3 or 2.7

Upvotes: 1

Related Questions