我有一个表单,用于发送具有相似名称的多个字段,但使用方括号将它们作为数组发送,键为“id”。我能够使用 foreach 循环成功地循环,但我的插入查询无法在数据库中进行任何更改。有任何线索说明原因吗?
这是表单中的代码:
$artist = mysql_fetch_array($allartists);
$allmusic = get_music_for_artist($artist_id);
$id = $music['id'];
while ($music = mysql_fetch_array($allmusic)) {
echo "<td class=\"td20 tdblue\">
<input name=\"song_title[" . $id . "]\" type=\"text\" value=\"" . $music['song_title'] . "\" />
</td>";
}
这是我的表单处理器上的代码
foreach ($_POST['song_title'] as $id => $song) {
$query = "UPDATE music SET
song_title = '{$song}'
WHERE id = $id ";
if (mysql_query($query, $connection)) {
//Success
header("Location: yourmusic.php?pid=3");
exit;
} else {
//Display error message
echo "update did not succeed";
echo "<p>" . mysql_error() . "</p>";
}
}
最佳答案
试试这个。
同时注意安全 http://www.phptherightway.com/#data_filtering
foreach ($_POST['song_title'] as $id => $song) {
$id = (int) $id;
$song = mysql_real_escape_string($song);
$query = "UPDATE music SET
song_title = '$song'
WHERE id = $id LIMIT 1;";
if (mysql_query($query, $connection)) {
//Success
header("Location: yourmusic.php?pid=3");
exit;
} else {
//Display error message
echo "update did not succeed";
echo "<p>" . mysql_error() . "</p>";
}
}
关于php - 插入多个具有相似名称的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17147781/