Wednesday, 7 December 2016

insert a primary key from one table as a foreign key to another table with php lastInsertId()

I am quite a newbie in PHP and MySQL so I need some help with correcting my code.
I have two tables - person and grades First table has columns id (auto increment), namesurname. Second one has columns id (auto increment), personIdgradePersonId holds a foreign key which is a primary key as id in the person table.
I insert data into the tables with the form then have php code to handle the data and insert it into my tables:
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$grade = $_POST['grade'];

if ($firstName) {
$insertPersonSQL = <<<EOT
INSERT INTO person (firstName, lastName)
VALUES (:firstName, :lastName);
INSERT INTO grade (grade)
VALUES (:grade);
EOT;

$insertPersonStatement = $db->prepare($insertPersonSQL);
$insertPersonStatement->execute([
  ':firstName' => $firstName,
  ':lastName' => $lastName,
  ':grade' => $grade,
  ]);
}
Then I try to insert a id from person to grade as person_id using lastInsert() to get the id:
$insertIdSQL = <<<EOT
INSERT INTO grade (person_id)
VALUES (:person_id);
EOT;
$insertIDStatement = $db -> prepare($insertIdSQL);
$lastId = $db->lastInsertId();
$insertIDStatement -> execute([
  ':person_id' => $lastId,
]);
However when I try to fill the form the person_id in the table grade gets the value of 0, the rest of the columns are ok. When I debug and echo the value of $lastId it's showed correctly.
What is wrong with the code? How to correct is so that the foreign key will be inserted correctly?

-----------------------------------------------------------------------------------------------------------------------

Best Answer;



Why adding the grade without a personId? Isn't it better do do it in one query like this:
// Get params
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$grade = $_POST['grade'];

if ($firstName) {
  // insert person
  $insertPersonSQL = <<<EOT
  INSERT INTO person (firstName, lastName)
  VALUES (:firstName, :lastName);
  EOT;

  $insertPersonStatement = $db->prepare($insertPersonSQL);
  $insertPersonStatement->execute([
    ':firstName' => $firstName,
    ':lastName' => $lastName
  ]);

  // insert grade
  $insertIdSQL = <<<EOT
  INSERT INTO grade (grade, person_id)
  VALUES (:grade, :person_id);
  EOT;
  $insertIDStatement = $db -> prepare($insertIdSQL);
  $lastId = $db->lastInsertId();
  $insertIDStatement -> execute([
    ':grade' => $grade,
    ':person_id' => $lastId
  ]);
}






No comments:

Post a Comment