0

I'm a real newbie to php and I just cant figure this out! I want different images to appear depending on what rating value is returned from the database.How do I do that?! This is the code:

    return '
        <div class="comment">
            <div class="name">'.$link_open.$d['name'].$link_close.'</div>
            <div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
            <div class="rating">'.$d['rating'].'</div>
            <p>'.$d['body'].'</p>
        </div>
    ';

So if the value is 5 I want the image 5stars.png to show up. I thought maybe you could write something like:

<img src="img/<?php echo $row['rating']; ?>stars.png">

But that won't work inside the return statement. What do I have to write to be able to write php inside the ? Is it even possible?

1
  • can you show me how you mean? lol Commented Oct 16, 2015 at 14:54

1 Answer 1

3

You would do it like this:

return '
    <div class="comment">
        <div class="name">'.$link_open.$d['name'].$link_close.'</div>
        <div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
        <div class="rating">'.$d['rating'].'</div>
        <p><img src="img/' . $d['rating'] . 'stars.png"></p>
    </div>
';

You can't use echo inside a string, as you have noticed. Instead, you use the . operator to concatenate strings.

Please note: this is a pretty basic question and not really suited for this site. I would recommend that you find a good tutorial on PHP basics and start there.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry, I've searched for the answer but haven't find it. This seemed so complicated so I thought my best shot at getting this right was to ask here. When I try that code, it wont read the rating value at all and just try to show "stars.png".
@Jenetic Well, you refer to $row in your question, but your return value originally had $d. You haven't posted enough info to make clear what you need, but I suspect you need to change $row['rating'] to $d['rating'].

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.