Show values from other tables in a loop

It seems to me that this is a rather convoluted way to work around the original problem. You are shy one axle, and need that axle to be in your database. You said that all values are added via a trigger in the database. If that is the case, why not add a value that has a distance of '0' with the id of the train. This will give you not only the axle, but the rendered div as well.

If your table looked like this after generation (please forgive me if the index is off in the wrong direction. I am struggling just a touch to understand your database layout):

+---------+----------+------+----------+
| axle_id | train_id | axle | distance |
+---------+----------+------+----------+
|       0 |        1 |    0 |        0 |
|       1 |        1 |    1 |     2500 |
|       2 |        1 |    2 |     5000 |
|       3 |        1 |    3 |     2500 |
+---------+----------+------+----------+

Then the following whould generate all circles, including the one that has a margin (or distance as you stated earlier) of '0'. Technically speaking, you have an axle with a distance of '0' from the front of the train, so why not track it in your database.

<div id="axles">
    <!--Here we create the axles and style them with the distances-->
    <?php
    $show_axle = $database->axles($_GET['train_id']);
    $total_distance = 0;
    foreach($show_axle as $number_ofaxles){
        // Because the first value is 0, the first run will be against the left edge.
        $total_distance += $number_ofaxles['distance']; ?>
        <div id="axle" name="test" style="margin-left:<?=$total_distance/25000*100;?>%">
            <?= "<div id='circle'>" . $number_ofaxles['axle'] . "</div>";?>
        </div>
    <?php } ?>
</div>

Taking this approach both simplifies and solves your problem.


Change

   $sql = "SELECT ti.axle_nr, ti.train_id, ti.bogie_nr, uti.axle_id, uti.train_id, uti.axle, uti.distance
            FROM bogie as ti
            JOIN axle as uti
            ON ti.train_id = uti.train_id
            WHERE ti.train_id = :train_id";

to

$sql = "SELECT ti.axle_nr, ti.train_id, ti.bogie_nr, uti.axle_id, uti.train_id, uti.axle, uti.distance
                    FROM bogie as ti
                    LEFT JOIN axle as uti
                    ON ti.train_id = uti.train_id AND uti.axle_id = ti.axle_nr
                    WHERE ti.train_id = :train_id";

Or run for testing next sql:

SELECT
      b.*,
      a.*
 FROM bogie AS b
 LEFT JOIN axle AS a ON a.train_id = b.train_id AND a.axle_id = b.axle_nr
WHERE b.train_id = 1

return 4 rows instead of 12.