PHP多对多表插入问题:$_POST提交无响应排查
问题排查与修复方案
嘿,我一眼就发现了导致表单无响应、数据无法写入的核心问题,咱们一步步来解决:
1. 提交按钮位置错误
你的提交按钮<input type="submit">写在了<form>标签的外面!浏览器只有在点击表单内部的提交按钮时,才会触发表单数据的提交操作。把按钮移到</form>之前就能解决提交无响应的问题。
2. 错误输出的语法问题
你在错误提示的echo语句里犯了字符串闭合错误,而且$conn->error的调用格式也不对——这会导致即使SQL执行出错,也没法正确输出错误信息,不利于后续排查问题。
修正后的完整代码
<form method='POST'> <?php include('connect_mysql.php'); if(isset($_POST["mangetilmange"])) { $song_id = $_POST["song_id"]; $artist_id = $_POST["artist_id"]; $sql ="INSERT INTO artist_has_song (song_id, artist_id) VALUES ('$song_id', '$artist_id')"; if($conn->query($sql)) { echo "Completed"; } else { // 修正了字符串闭合和错误输出的格式 echo "插入失败: $sql <br> 错误信息: " . $conn->error; } } ?> <p>Song Name</p> <?php $sql = "SELECT * FROM song"; $resultat = $conn->query($sql); echo "<select name='song_id'>"; while ($rad = $resultat->fetch_assoc()) { $song_id = $rad["song_id"]; $songname = $rad["songname"]; echo "<option value='$song_id'>$songname</option>"; } echo "</select>"; ?> <p>Artist Name</p> <?php $sql = "SELECT * FROM artist"; $resultat = $conn->query($sql); echo "<select name='artist_id'>"; while ($rad = $resultat->fetch_assoc()) { $artist_id = $rad["artist_id"]; $artistname = $rad["artistname"]; echo "<option value='$artist_id'>$artistname</option>"; } echo "</select>"; ?> <!-- 把提交按钮移到表单内部 --> <input type="submit" name="mangetilmange" value ="Submit"> </form>
额外提示(可选)
虽然你提到忽略SQL注入问题,但还是建议后续项目中使用预处理语句来避免安全风险,比如:
$stmt = $conn->prepare("INSERT INTO artist_has_song (song_id, artist_id) VALUES (?, ?)"); $stmt->bind_param("ii", $song_id, $artist_id); // 假设song_id和artist_id都是整数类型 $stmt->execute();
内容的提问来源于stack exchange,提问作者Mads Frost
相关产品推荐
相关产品推荐

