Said Thaher
Said Thaher

Reputation: 23

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

I have three tables: users, courses and grads.

I have a form to add a new user which include a dropdown list which shows the available courses with the value "id" from courses table.

When a course been added to the database the dropdown list will be updated.

Now, what I try to do is:

When I use the form to add new user and I choose the course from the dropdown list, I want the same value for the course being choosen sent to the grades table (course_id) and the (user_id) which will be added with the same submit action.

I use Wrapper classes php and PDO, just explain with normal 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>

I added this code after $user->create so its look like that

$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'),
                    ));

but i got this error : Fatal error: Call to undefined function LAST_INSERT_ID() in C:\xampp\htdocs\Jensenonline1\register.php on line 77

Upvotes: 0

Views: 93

Answers (1)

Barmar
Barmar

Reputation: 780688

Use the LAST_INSERT_ID() function in MySQL to get the ID that was assigned to the user that was just created. Create the new user with a query like this:

$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']));

Then to add to grades, use:

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

Since you use the same $_POST['course_id'] when executing both queries, the same value will be put in both tables.

Upvotes: 0

Related Questions