更新mysql表中多列的php脚本

4szc88ey  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(298)

我需要在一个数据库的一个表中更新多个列。现在,当我运行php脚本时,它只完成了第一个update命令,不会更新它后面的条目。我不确定这有什么问题:

<?php
$servername = "localhost";
$username = "user";
$password = "pw";
$dbname = "database";

//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if($conn->connect_error) {
        die("Connection failed:" . $conn->connect_error);
}

$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";

if (mysqli_query($conn, $sql)) {
        echo "Record updated successfully";
} else {
        echo "Error updating record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

当我从命令行运行它时,它不会出错,它会很好地运行第一次更新。当我检查数据库时,它实际上已经将id为“10”的“topic\u id”列中的“team\u id”更新为“15”,但是其他两列没有更新。为什么会这样?

plicqrtu

plicqrtu1#

只需使用“or”操作符就可以修复它!

$sql = "UPDATE ost_help_topic SET team_id='15' WHERE topic_id=10 OR topic_id=12 OR topic_id=13"
lbsnaicq

lbsnaicq2#

你一遍又一遍地定义同一个变量,用脚踩着以前的版本。只有最后一个定义“粘住”并运行。
切换到数组:

// 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)

其中一个查询可以将多个值更新为同一事物。

zd287kbt

zd287kbt3#

您需要执行每一行:

//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);
    }
}

相关问题