如何更新一个表中的多行(mysql,php,pdo)

时间:2018-06-21 19:08:02

标签: php mysql pdo

This is my form是当我将文本区域留空时,我希望它删除该条目

Not delete the whole row

我有一个要在其中更新主键(RegNo)和(Name)的表

                              Table students
(Primary Key)                                            (Foreign Key)
 RegNo               Name              Passwd             ProjectID
 f12345              Ali                345                   1
 f12346             Chris               346                   1
 f12347             Ameer               347                   1

我尝试了几种方法,

$names = [
       ['reg'=> $_POST['s1_id'], 'name'=> $_POST['s1_name']],
       ['reg'=> $_POST['s2_id'], 'name'=> $_POST['s2_name']], 
       ['reg'=> $_POST['s3_id'], 'name'=> $_POST['s3_name']]
       ]; 

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

 foreach ( $names as $name)
 {
   try
  {

    $stmt = $conn->prepare( $query );  
    $stmt->bindParam(':Name', $name['name']);
    $stmt->bindParam(':reg', $name['reg']);

    $result = $stmt->execute();
    $msg = "Record updated";

    //header("location:adminhome.php");
  }

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

通过这种方式,我只能更新“名称”列。我如何更新RegNo和Name。我是后端编程的新手。不知道如何实现这一目标。

1 个答案:

答案 0 :(得分:1)

像这样?我只在, RegNo=:reg内添加了SET,因为reg已经绑定,我认为这就是您需要添加的全部内容。

我更新了我的答案,因为当您发送带有数据结构的更新的RegNo时,它将永远不会匹配。因此,您应该发送两个RegNo,一个是旧的,另一个是新的。

对于删除,我定义了两个查询,一个查询用于删除,一个查询用于更新。在更新结果之前,我在foreach内检查新的学生ID($name['reg_set'])是否为空,如果是,则运行$query_delete,否则将运行$query_update < / p>

$names = [
       ['reg'=> $_POST['s1_id'], 'reg_set'=> $_POST['s1_id_set'], 'name'=> $_POST['s1_name']],
       ['reg'=> $_POST['s2_id'], 'reg_set'=> $_POST['s2_id_set'], 'name'=> $_POST['s2_name']],
       ['reg'=> $_POST['s3_id'], 'reg_set'=> $_POST['s3_id_set'], 'name'=> $_POST['s3_name']]
       ];

 $query_delete="DELETE FROM students  WHERE RegNo=:reg And ProjectID='$id'";

     $query_update="UPDATE students SET Name=:Name, RegNo=:reg_set WHERE RegNo=:reg And
     ProjectID='$id'";

 foreach ( $names as $name)
 {
   try
  {

            if(empty($name['reg_set'])){
                $stmt = $conn->prepare( $query_delete );
                $stmt->bindParam(':Name', $name['name']);
                $stmt->bindParam(':reg', $name['reg']);

                $result = $stmt->execute();
                $msg = "Record deleted";
            }else{
                $stmt = $conn->prepare( $query_update );
                $stmt->bindParam(':Name', $name['name']);
                $stmt->bindParam(':reg', $name['reg']);
                $stmt->bindParam(':reg_set', $name['reg_set']);


                $result = $stmt->execute();
                $msg = "Record updated";
            }


    //header("location:adminhome.php");
  }

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