i'm using php to create a student registration system and i have created a database that has 6 tables
student_reg,
academics,
nextofkin,
contacts,
postal,
residential
and the primary key for student_reg is used as foreign key in the remaining 5 tables so i was trying to use last_insert_id() function to retrieve the primary key of student reg and insert it into the foreign key of the 5 tables. it does insert into the foreign key but the problem is that it inserts the correct id into one table but the rest receives a different id. insertAnyData is used to insert student_reg and insert Any is used to insert the remaining tables. WHAT HAVE I DONE WRONG or WHAT AM I MISSING. here is my code
public function insertAnyData($table, $fields = array())
{
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach ($fields as $field){
$values .= '?';
if ($x < count($fields)){
$values .= ', '; //coma and space
}
$x++;
}
//die($values);
$sql = "INSERT INTO {$table} (`".implode('`, `', $keys)."`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()){
return true;
}
//}
return false;
}
public function insertAny($table, $fields = array())
{
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach ($fields as $field){
$values .= '?';
if ($x < count($fields)){
$values .= ', '; //coma and space
}
$x++;
}
//die($values);
$sql = "SET @last_id_in_student_reg=LAST_INSERT_ID();
INSERT INTO {$table} (`".implode('`, `', $keys)."`,idstudent_reg) VALUES ({$values},@last_id_in_student_reg)";
if(!$this->query($sql, $fields)->error()){
return true;
}
//}
return false;
}