dst2017 2014-04-11 23:32
浏览 22
已采纳

如何将相同的值插入到表sql,php中

can someone help me with this, Im using a simple form to add user into a database, my goal is to add the user into one table, but at the same time add the (userid) into a different table, the user id is made automatically by the database, it is possible to do this ?

Thank you

 <?php 
    require("coneccion.php"); 

    if(!empty($_POST))
    { 

      $query = "INSERT INTO students (fname, lname, studentcode) values (:fname, :lname, :studentcode)";
      $query_params = array(':fname' => $_POST['fname'], ':lname' => $_POST['lname'], ':studentcode' => $_POST['studentcode']);

      try
      {
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
      }
      catch(PDOException $ex)
      {
        die("Error" . $ex->getMessage());
      }
      $name = $_SESSION['user']['username'];
      $id = $_SESSION['courseid'];
      $query = "INSERT INTO idtables(courseid, studentid) values ('$id', (SELECT id FROM users WHERE username = '$name'))";
      try
      {
        $stmt = $db->prepare($query);
        $stmt->execute();
      }
      catch(PDOExecute $ex)
      {
        die("Error" . $ex->getMessage());
      }
      $id = $_SESSION['courseid'];
      header("Location: index.php?id=$id");
      die("Rendirecting to index.php?id=$id");

    }
    ?>

    <?php
    $id = $_SESSION['courseid'];
    echo $id;
    ?>

    <form action="add.php" method="post">
      First Name: <input type="text" name="fname" value=""><br>
      Last Name: <input type="text" name="lname" value=""><br>
      Stude Code: <input type="text" name="studentcode" value=""><br>
      <input type="submit" value="Add Student">
    </form>
  • 写回答

3条回答 默认 最新

  • dongxun1244 2014-04-11 23:37
    关注

    You can get the id of the row you added like this :

    $studentId = $db->lastInsertId();
    

    See docs

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据