Jump to content

Display an image a certain number of times depending on a value in database


Go to solution Solved by Psycho,

Recommended Posts

Hi Everyone
 
I am working on a website for a school project that displays the rating for a game in the form of a star image. If the game has a rating of 3, 3 stars need to be displayed etc. The ratings are stored in a database on phpmyadmin. 
 
database = assessment
table = games
column = rating
 
Each game has a gameID, there are 31 games on the table and looks like this
http://imgur.com/a/6F74I

 

This is how the code is looking for this particular part of the webpage. The new line of code will go underneath the <img src="images line. 
 

<div class="game">
    <a class="cat" href="index.php?page=game&gameID=<?php echo $game_rs['gameID']; ?>">
        <p><?php echo $game_rs['game']; ?></p>
        <p><?php echo $game_rs['developer']; ?></p>
        <img src="images/thumbnails/<?php echo $game_rs['thumbnail']; ?>"></img>
    </a>
</div>

 

I really appreciate any help anyone can offer :)

Thankyou!!!

Read up on the "heredocs" operator while you're doing your research.  It will make that html/php jumble of code a lot easier to write and to read later on.

 

 

echo HEREDOCS
<div class="game">
    <a class="cat" href="index.php?page=game&gameID={$game_rs['gameID']}">
        <p>{$game_rs['game']}</p>
        <p>{$game_rs['developer']}</p>
        <img src="images/thumbnails/{$game_rs['thumbnail'}"></img>
    </a>
</div>
HEREDOCS;
  • Solution

Instead of creating a loop, a more elegant approach might be to use the str_repeat() function.

 

Create a variable to hold the content for a star image element and then just use str_repeat() with that variable and the rating number to create the correct output.

 

So, somewhere before the loop to create the output for the records define the image

$starImg = "<img src='images/star.jpg'>";

Then within the loop for the records, use a single line to create the correct number of images using the rating number from the query results

echo str_repeat($starImg, $game_rs['rating_number']);
Edited by Psycho
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.