我需要更新单个数据库中单个表中的多个列。 现在,当我运行PHP脚本时,它仅完成第一个UPDATE命令,而不会更新其后的条目。我不确定这是怎么回事:
sudo service nginx restart
当我从命令行运行它时,它不会出错,它确实可以运行第一个更新。当我检查数据库时,实际上它已将ID为“ 10”的“ topic_id”列中的“ team_id”更新为“ 15”,但其他两列未更新。为什么会这样?
答案 0 :(得分:3)
您要一遍又一遍地定义相同的变量,从而踩踏以前的版本。仅最后一个定义会“保留”并运行。
切换到数组:
// Define an array
$sql = [ ];
// Append to the array each query
$sql[] = "UPDATE ost_help_topic SET team_id='15' WHERE topic_id=10";
$sql[] = "UPDATE ost_help_topic SET team_id='15' WHERE topic_id=17";
$sql[] = "UPDATE ost_help_topic SET team_id='15' WHERE topic_id=22";
foreach($sql as $q) {
// Run query.
}
或使用IN (...)
方法:
UPDATE ost_help_topic SET team_id='15' WHERE topic_id IN (10,17,22)
其中一个查询可以将多个值更新为相同。
答案 1 :(得分:1)
您需要执行每一行:
//1
$sql="UPDATE ost_help_topic SET team_id='15' WHERE topic_id=10";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
//2
$sql="UPDATE ost_help_topic SET team_id='15' WHERE topic_id=17";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
//2
$sql="UPDATE ost_help_topic SET team_id='15' WHERE topic_id=22";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
或创建一个数组
$arra = array();
$arra[]="UPDATE ost_help_topic SET team_id='15' WHERE topic_id=10";
$arra[]="UPDATE ost_help_topic SET team_id='11' WHERE topic_id=12";
$arra[]="UPDATE ost_help_topic SET team_id='12' WHERE topic_id=13";
和foreach:
foreach ($arra as $sql) {
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
}
答案 2 :(得分:0)
仅使用“或”运算符即可解决问题!
$sql = "UPDATE ost_help_topic SET team_id='15' WHERE topic_id=10 OR topic_id=12 OR topic_id=13"