php – play button plays another audio

Question:

I have a table called posts , and in it there is a post_aud column where a text is 'inserted' with the name of the audio/song (which is 'saved' in the audios folder)…

$get_posts = "SELECT * FROM posts ORDER by 1 DESC";
$run_posts = mysqli_query($db,$get_posts);
while ($row_posts=mysqli_fetch_array($run_posts)){
$post_aud = $row_posts['post_aud'];

<div name='barra'>
  <i id='play' onclick='play();'></i>
  <i id='pause' onclick='pause();'></i>
<audio id='song' >
   <source src='../audios/$post_aud' type='audio/ogg'>
   <source src='../audios/$post_aud' type='audio/mpeg'>
</audio>

//javascript

function play() {
  document.getElementById('song').play();
}

function pause() {
  document.getElementById('song').pause()
}

// javascript date

</div> //fecha barra
} //fecha while

In other words, each post has its post_aud/music, however, the problem is that every time I press play (on any post) it only plays the audio from the last post inserted (so much so that if I use the normal html player, it works fine). Any idea what it might be??? Grateful!!!

Answer:

It is creating several elements with the same id and creating several unnecessary scripts in the loop . The correct thing would be to create a count $conta that would be a way to identify each element:

<?php

$get_posts = "SELECT * FROM posts ORDER by 1 DESC";
$run_posts = mysqli_query($db,$get_posts);
$conta = 0;
while ($row_posts=mysqli_fetch_array($run_posts)){
   $post_aud = $row_posts['post_aud'];
?>
<div name='barra<?=$conta?>'>
  <i onclick='play('<?=$conta?>');'></i>
  <i onclick='pause('<?=$conta?>');'></i>

   <audio id='song<?=$conta?>' >
      <source src='../audios/<?=$post_aud?>' type='audio/ogg'>
      <source src='../audios/<?=$post_aud?>' type='audio/mpeg'>
   </audio>
</div>
<?php
   $conta++;
} //fecha while
?>

<script>
function play(id) {
  document.getElementById('song'+id).play();
}

function pause(id) {
  document.getElementById('song'+id).pause()
}
</script>   
Scroll to Top