使用不同的值更新一个数据库表列

时间:2018-06-13 11:35:29

标签: php mysql

我想用最多三个值更新表,用两个值更新最小值。如何更新表。我从表格中获取价值,三个学生有三个领域。现在,当我在数据库中更新它们时,它们都具有相同的值。现在我正在尝试这个原因。不知道它是否有效 请参阅我的页面This is the form where i get values from database and then want to update there are three student name fields (with different name and id in html form but at back end they are stored in one table column)

$s1_name=$_POST['s1_name'];
$s2_name=$_POST['s2_name'];
$s3_name=$_POST['s3_name'];

$query="update students SET Name=:Name
WHERE ProjectID='$id'
";

try
{

 $stmt = $conn->prepare( $query );  
 $stmt->bindParam(':Name', $s1_name);
 $stmt->bindParam(':Name', $s2_name);
 $stmt->bindParam(':Name', $s3_name);
 $result = $stmt->execute();
 $msg = "Record updated";
 }

 catch(PDOException $ex)
 {
  $msg = $ex -> getMessage();
 }

 } 

1 个答案:

答案 0 :(得分:0)

这种方式不起作用。您执行此操作的方式将导致查询仅更新<?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(); } }

您必须为每个查询执行try / catch语句:

window?.tintColor = myColor