如何在PHP的if语句中嵌入.wav文件?附语法错误解决求助
Hey there! No worries at all as a beginner—we all start here. Let's break down and fix the two main issues in your code:
1. Syntax Error from Unescaped Quotes
Your echo statement uses double quotes (") for the outer string, but you're also using double quotes inside for the src and type attributes. PHP gets confused because it thinks the string ends early when it hits the second ".
You have two easy fixes here:
- Use single quotes (
') for the inner attributes, so the outer double quotes don't clash - Or escape the inner double quotes with a backslash (
\")
2. Logic Error: Assignment Instead of Comparison
In your if condition, you wrote if ($sound = "1")—this is an assignment (=), not a comparison. This will always set $sound to "1" and make the condition evaluate to true, which isn't what you want. You need to use either == (loose comparison) or === (strict comparison, better practice here since you're checking against a string).
Also, note that your original $sound = $row['sound']; line is outside the while loop, so it will only hold the value from the last row in your result set. If you want to check each row's sound value, you should move the if statement inside the loop.
Corrected Full Code
<?php $result = $db->query("SELECT * FROM my_table WHERE sound=1"); while($row = $result->fetch_assoc()){ echo $row['sound']; // Check sound value inside the loop to handle each row $sound = $row['sound']; if ($sound === "1"){ // Using single quotes for inner attributes to avoid clash echo "<audio autoplay><source src='/sounds/beep.wav' type='audio/wav'></audio>"; } } ?>
Quick Notes
- I removed the extra
autoplayfrom the<source>tag—it only needs to be on the<audio>tag - Using
===ensures we're checking both value and type (if yoursoundcolumn is an integer, you could use=== 1instead)
内容的提问来源于stack exchange,提问作者Barrett K

