Add a fixed image sequence in PHP

Asked

Viewed 29 times

0

I own 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 placements to receive an image of a medal before the numbering of the position, ex: gold medal for first, silver for second and bronze for third. It is set to 10 placements.

1 answer

1


Has many ways.

Here we create a array with 3 names:

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

And a if inline (ternary parole):

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

Applying in 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;
  } 
  ?>
  • Thank you very much friend, helped me a lot.

  • I left an alternative version to facilitate reading

  • Boy, you are 10 even.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.