You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP的if语句中嵌入.wav文件?附语法错误解决求助

Fixing Your PHP Audio Playback Syntax & Logic Issues

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 autoplay from the <source> tag—it only needs to be on the <audio> tag
  • Using === ensures we're checking both value and type (if your sound column is an integer, you could use === 1 instead)

内容的提问来源于stack exchange,提问作者Barrett K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:02:53