foreach循环更新表中的最后一次值三次

时间:2018-06-13 13:15:31

标签: php mysql

See this picture of my page 这是使用foreach循环更新表的代码。但它更新了最后一次值,即POST [s3_name]

<?php
$names = [$_POST['s1_name'], $_POST['s2_name'], $_POST['s3_name']];
$query = "update students SET Name=:Name WHERE ProjectID='$id'";


foreach ($names as $name) {
try
{
    $stmt = $conn->prepare($query);  
    $stmt->bindParam(':Name', $name);
    $result = $stmt->execute();
    $msg = "Record updated";
}
catch(PDOException $ex)
{  
   $msg = $ex -> getMessage();
}
}

1 个答案:

答案 0 :(得分:0)

你可以从某个地方获取id并循环它。像这样的东西

$names = [
    ['id' => 1, 'name' => 'name1'],
    ['id' => 2, 'name' => 'name2'],
    ['id' => 3, 'name' => 'name3']
];


foreach ($names as $name) {
    try {
        $query = "update students SET Name=:Name WHERE ProjectID=:Id";

        $stmt = $conn->prepare($query);  
        $stmt->bindParam(':Name', $name['name']);
        $stmt->bindParam(':Id', $name['id']);
        $result = $stmt->execute();
        $msg = "Record updated";
    } catch(PDOException $ex) {  
        $msg = $ex -> getMessage();
    }
}