0

I want to be able to play all of the audio files in my database via by embedding the source in a player.

I have created an sql query that will return an array containing all of my mp3 names.

I then use a while loop

while($row = mysqli_fetch_array($result)) {
$sourcefile=$row['location'];
echo '<audio controls>';
echo '<source src="$sourcefile" type="audio/mpeg">';
echo "$sourcefile";
echo '</audio>';
}

Which results in the following html:

<audio controls>
<source src="$sourcefile" type"audio/mpeg">
</audio>

If I explicitly substitute the $sourcefile, within the audio tag, with songname.mp3 it works just fine.

And just to make sure the php variable is getting the correct value, I used an echo statement to see the value it contained and it is indeed songname.mp3.

What could possibly be wrong?

  • 2
    [What is the difference between single-quoted and double-quoted strings in PHP?](http://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php) – Halvor Holsten Strand Jul 29 '14 at 02:38

2 Answers2

2

Variable substitution only happens inside double-quoted strings, not single-quoted strings. Change it:

echo "<source src='$sourcefile' type='audio/mpeg'>";
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You can try this:

echo "<source src='{$sourcefile}' type='audio/mpeg'>";

Or this:

<source src="<?php echo $sourcefile; ?>" type="audio/mpeg">

Remember (HTML & PHP) don't mix without their tags :)

MAZux
  • 911
  • 1
  • 15
  • 28
  • The `"` after `src=` ends the string, so that won't work. And you're missing `=` after `type`. – Barmar Jul 29 '14 at 06:28
  • Thanx about `=` after `type`. But about the `"` after `src=` it works , because I used **`{}`** not `.$sorcefile.` , try it by yourself. – MAZux Jul 29 '14 at 07:51
  • I suggest you try it, you should get a syntax error. – Barmar Jul 29 '14 at 07:53
  • I just tried it, I got `Parse error: parse error, expecting \`','' or \`';'' ` – Barmar Jul 29 '14 at 07:55
  • Now it works, it's the same as my answer. You don't need the `{}` since it's a simple variable. – Barmar Jul 29 '14 at 08:00