A
A
Alex_ART2017-04-08 15:50:40
PHP
Alex_ART, 2017-04-08 15:50:40

How not to cheat in this example?

hello world!
Self-taught, I am practicing writing code, now I am making an online store, in general, I have
the essence of the issue Tablets - picture in A / tablets / .. Laptops - picture in A / laptops / .. Phones - picture in A / phones / .. But for example I need to display top 5 viewed products - and for each product, the picture is in a separate folder. This is how I screwed it up

<?php
 $views = mysqli_query($connection, "SELECT * FROM `goods` ORDER by `views` DESC limit 5");
                    while ($top_views = mysqli_fetch_assoc($views)) { ?>
                        <article class="article">
                            <div class="article__image" style="background-image: url(/media/images/<?php
                            if ($top_views['categorie_id'] == 1) {
                                echo "tablet/";
                            } elseif ($top_views['categorie_id'] == 2) {
                                echo "phones/";
                            } else {
                                echo "nouts/";
                            }
                            echo $top_views['img'];
                            ?>
                            "></div>

Everything works, but it looks a lot like a piece of g *** and not like code, how can I do it better?
Tell a noob)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2017-04-08
@Alex_ART

Variants
of using OOP will solve this problem, by adding a method to
write a function for this, which will return the required url
to store the full url in the database
. But your method is not super G either. But instead of if, you should at least use switch case. Or an array like

<?php $arr = [2=>'/tablet',18=>'phones/']; ?>
<div class="article__image" style="background-image: url(/media/images/<?= $arr[$top_views['categorie_id']]?>"></div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question