在两个不同的表中插入一个来自第三个表的foregin键,以相同的形式提交


Insert into two diffrent tables a foregin key from third table in same form submit

我有三个表:用户、课程和毕业生。

  • users表(id、username、pass、course_id)
  • 课程表(id、课程名称、说明)
  • 梯度表(user_id、course_id、grade)

我有一个添加新用户的表单,其中包括一个下拉列表,显示课程表中值为"id"的可用课程。

将课程添加到数据库后,下拉列表将更新。

现在,我要做的是:

当我使用表单添加新用户并从下拉列表中选择课程时,我希望将所选课程的相同值发送到成绩表(course_id)和(user_id),后者将通过相同的提交操作添加。

我使用Wrapper类php和PDO,只是用普通的PDO来解释。

<?php
require_once 'core/init.php';
include 'includes/header.php';
include 'includes/headeradmin.php';

if(Input::exists()) {
    if(Token::check(Input::get('token'))) {   ### Security check
   $validate = new Validate();
   $validation = $validate->check($_POST, array(
    'email' => array(
        'required' => true,
        'min'      => 2,
        'max'      => 20,
        'unique'   => 'users'
    ),
    'password' => array(
        'required'  => true,
        'min'       => 6
    ),
    'password_again' => array(
        'required'  => true,
        'matches'   => 'password'
    ),
    'fullname' => array(
        'required'  => true,
        'min'       => 2,
        'max'       => 20
    ),
    'group_id' => array(
        'min'       => 1,
        'max'       => 20
    ),
    'class_id' => array(
        'min'       => 1,
        'max'       => 20
    ),
    'course_id' => array(
        'min'       => 1,
        'max'       => 20
    )
));

if($validation->passed()) {
            $user = new User();
            $salt = Hash::salt(32);
            try {
            $user->create(array(
                'email' => Input::get('email'),
                'password' => Hash::make(Input::get('password'), $salt),
                'fullname' => Input::get('fullname'),
                'address'  => Input::get('address'),
                'telnumber'=> Input::get('telnumber'),
                'salt'     => $salt,
                'group_id' => Input::get('group_id'),
                'class_id' => Input::get('class_id'),
                'course_id'=> Input::get('course_id'),
                ));

                    echo "En ny användaren Har skapat";
                #Session::flash('home', 'you are registerd successfully');
                #Redirect::to('index.php');
            } catch (Exception $e) {
                die ($e->getMessage());
            }
        #Session::flash('success', 'You registered successfully');
        #header('Location: index.php');
   } else {
      foreach($validation->errors() as $error) {
        echo $error,'<br>';
      }
    }
}  
}
?>

<form  id ="regform" action="" method="post">
    <div id="register">
    <table>
        <tr>
        <td style="width:130px; text-align: right"><label for="email">Email:</label></td>
        <td style="width: 200px"><input type="email" name="email" id="email" value="<?php echo escape(Input::get('email')); ?>" autocomplete="off" width="200px"></td>
    </tr>
   <tr>
        <td style="width:130px; text-align: right"><label for="password">Password:</label>
        <td style="width: 200px"><input type="password" name="password" id="password" width="200px"></td>
    </tr>
    <tr>
        <td style="width:130px; text-align: right"><label for="password_again">Re Enter your password:</label></td>
        <td style="width: 200px"><input type="password" name="password_again" id="password_again" width="200px"></td>
    </tr>
   <tr>
        <td style="width:130px; text-align: right"><label for="fullname">Full Name:</label></td>
        <td style="width: 200px"><input type="text" name="fullname" id="fullnmae" value="<?php echo escape(Input::get('fullname')); ?>" autocomplete="off" width="200px"></td>
    </tr>
    <tr>
        <td style="width:130px; text-align: right"><label for="address">Address:</label></td>
        <td style="width: 200px"><input type="text" name="address" id="address" width="200px"></td>
    </tr>
    <tr>
        <td style="width:130px; text-align: right"><label for="telnumber">Tel. Number:
        </label></td>
        <td style="width: 200px"><input type="text" name="telnumber" id="telnumber" width="200px"></td>
    </tr>
   <tr>
        <td style="width:130px; text-align: right"><label for="group_id">Permission:</label></td>
        <td style="width: 200px; text-align: center"><select name="group_id" width="200px">
        <option value="0">Select a permission</option>
        <option value="1">Student</option>
        <option value="2">Admin</option>
        <option value="3">Teacher</option>
        </select></td>
 </tr>
    <tr>
        <td style="width:130px; text-align: right"><label for="class_id">Class:</label></td>
        <td style="width: 200px; text-align: center"><select name="class_id" width="200px">
        <option value="0">Select a Class</option>
        <?php 
            $class = DB::getInstance()->query("SELECT * FROM classes");
                foreach ($class->results() as $class) {
        echo '<option value="'. $class->id .'">' . $class->classname . '</option>';
        }
        ?>
        </select></td>
    </tr>
    <tr>
        <td style="width:130px; text-align: right"><label for="course_id">Course:</label></td>
        <td style="width: 200px; text-align: center"><select name="course_id" width="200px">
        <option value="0">Select a Course</option>
        <?php 
            $course = DB::getInstance()->query("SELECT * FROM courses");
                foreach ($course->results() as $course) {
        echo '<option value="'. $course->id .'">' . $course->coursename . '</option>';
        }
        ?>
        </select></td>
    </tr>
    <tr>
    <td style="width:130px; text-align: right"></td>
    <td style="width: 200px"><input type="hidden" name="token" value="<?php echo Token::generate(); ?>"></td>
    </tr>
    <tr>
       <td style="width:130px; text-align: right"></td>
        <td style="width: 200px; text-align: center"> <input type="submit"  value="Register"></td>
    </tr>
    </table>

我在$user->create之后添加了这个代码,所以它看起来像

$user->create(array(
                'email' => Input::get('email'),
                'password' => Hash::make(Input::get('password'), $salt),
                'fullname' => Input::get('fullname'),
                'address'  => Input::get('address'),
                'telnumber'=> Input::get('telnumber'),
                'salt'     => $salt,
                'group_id' => Input::get('group_id'),
                'class_id' => Input::get('class_id'),
                'course_id'=> Input::get('course_id'),
                ));
                $grad = DB::getInstance()->insert('grads', array(
                        'user_id' => Input::get(LAST_INSERT_ID()),
                        'course_id' => Input::get('course_id'),
                    ));

但我得到了这个错误:致命错误:在第77行调用C:''examplep''htdocs''Jensenline1''register.php中未定义的函数LAST_INSERT_ID()

使用MySQL中的LAST_INSERT_ID()函数来获取分配给刚刚创建的用户的ID。使用如下查询创建新用户:

$stmt1 = $pdo->prepare("INSERT INTO users (username, pass, course_id) 
                        VALUES (:username, :pass, :course_id)");
$stmt1->execute(array(':username' => $_POST['username'],
                      ':pass' => $_POST['password'],
                      ':course_id' => $_POST['course_id']));

然后添加到grades,使用:

$stmt2 = $pdo->prepare("INSERT INTO grades (user_id, course_id)
                        VALUES (LAST_INSERT_ID(), :course_id)");
$stmt2->execute(array(':course_id' => $_POST['course_id']));

由于在执行两个查询时使用相同的$_POST['course_id'],因此在两个表中都将放入相同的值。