Add an "id" to an element created in PHP


I'm starting with PHP and I have a doubt, maybe a little basic, but the truth is that I can not solve it. What I'm trying to do is create something like a traffic light where the images are changed every so often, depending on the color they have in the database as seen in the image below.

I have this little code in PHP that allows me to create the circles that I intend to show on my website:

for ($i = 1; $i <= $cant_est; $i++) {

    if ($estacion['color'] == 'verde') {
        ?><img src="<?= base_url() ?>/images/verde.png"> <?php
    } elseif ($estacion['color'] == 'rojo') {
        ?><img src="<?= base_url() ?>/images/rojo.png"> <?php
    } elseif ($estacion['color'] == 'amarillo') {
        ?><img src="<?= base_url() ?>/images/amarillo.png"><?php

What that code does is show the number of circles, according to the number of stations I have (in this case 2 stations) so on my page it appears like this:

How to assign an "id" to each circle that is created? For example, I want to change the color of one of the two stations in my database, but I do not know how to identify them.

asked by EEBB 06.11.2016 в 02:05

2 answers


If you want to put the id_estacion of the database, you should do a foreach instead of a for :

foreach ($query->result_array() as $estacion) {

  echo '<img id="'.$estacion['id_estacion'].'" src="'.base_url().'/images/'.$estacion['color'].'.png">';    

This way you do not need to compare it with a if else if , since it returns the same name of color of the database: $estacion['color'].png .

answered by 07.11.2016 в 01:03

Within the cycle, as you assign the src to each image, add the id of it based on the number of the iteration

<img id="<?php echo $i ?>" src="<?php echo  base_url()."/images/verde.png" ?>">

Stopping a little, the id would not be the iteration number, but the identifier in the "station" DB

answered by 06.11.2016 в 02:09