Add a fixed image sequence in PHP

0

I have this code:

<table class"is-bordered is-striped is-narrow is-hoverable is-fullwidth">
  <tr align="center" id="title">
    <td>POSIÇÃO</td>
    <td>NOME</td>
    <td>MATOU</td>
    <td>MORREU</td>
  </tr>


  <?PHP 
  $tabela = mysqli_query($connecta, "SELECT * FROM pvpm_data ORDER BY kills DESC LIMIT 10");
  $pos = 1;

  while($pvp = mysqli_fetch_assoc($tabela)){
  echo '
  <tr align="center" id="player">

    <td>'.$pos.'º</td>
    <td>'.$pvp['name'].'</td>
    <td>'.$pvp['kills'].'</td>
    <td>'.$pvp['dies'].'</td>

  </tr>
  ';

  $pos++;
  } 
  ?>
</table>

It refers to a ranking of a game, and I would like the first 3 placings to receive an image of a medal before the position numbering, eg gold for first, silver for second and bronze for third. It is set to 10 settings.

    
asked by anonymous 12.10.2018 / 17:11

1 answer

1

There are many ways.

Here we create an array with 3 names:

  $img[1] = 'ouro.jpg';
  $img[2] = 'prata.jpg';
  $img[3] = 'bronze.jpg';

And a if inline (ternary conditional):

( $pos<4  ?  '<img src="'.$img[$pos].'">'  :  '' )
// ^-- se verdadeiro  ^-- retorna isto        ^-- senão retorna isto    

Applying to your code:

<table class"is-bordered is-striped is-narrow is-hoverable is-fullwidth">
  <tr align="center" id="title">
    <td>POSIÇÃO</td>
    <td>NOME</td>
    <td>MATOU</td>
    <td>MORREU</td>
  </tr>


  <?PHP 
  $tabela = mysqli_query($connecta, "SELECT * FROM pvpm_data ORDER BY kills DESC LIMIT 10");
  $pos = 1;
  $img[1] = 'ouro.jpg';
  $img[2] = 'prata.jpg';
  $img[3] = 'bronze.jpg';

  while($pvp = mysqli_fetch_assoc($tabela)){
  echo '
  <tr align="center" id="player">
    <td>'.$pos.'º'.($pos<4?'<img src="'.$img[$pos].'">':'').'</td>
    <td>'.$pvp['name'].'</td>
    <td>'.$pvp['kills'].'</td>
    <td>'.$pvp['dies'].'</td>
  </tr>
  ';

  ++$pos;
  } 
  ?>
</table>

The same logic, but easier to read:

<?PHP 
  $tabela = mysqli_query($connecta, "SELECT * FROM pvpm_data ORDER BY kills DESC LIMIT 10");
  $pos = 1;
  $img[1] = 'ouro.jpg';
  $img[2] = 'prata.jpg';
  $img[3] = 'bronze.jpg';

  while($pvp = mysqli_fetch_assoc($tabela)){
  if ($pos < 4 ) {
     $medalha = '<img src="' . $img[$pos] . '">';
  } else {
     $medalha = '';
  }
  echo '
  <tr align="center" id="player">
    <td>'.$pos.'º'.$medalha.'</td>
    <td>'.$pvp['name'].'</td>
    <td>'.$pvp['kills'].'</td>
    <td>'.$pvp['dies'].'</td>
  </tr>
  ';

  ++$pos;
  } 
  ?>
    
12.10.2018 / 17:21