0

我正在使用 php 创建一个学生注册系统,并且我创建了一个包含 6 个表的数据库

student_reg,
academics,
nextofkin,
contacts,
postal,
residential

并且student_reg的主键在其余 5 个表中用作外键,所以我试图使用last_insert_id()函数来检索 student reg 的主键并将其插入到 5 个表的外键中。它确实插入到外键中,但问题是它将正确的 id 插入到一个表中,但其余的接收到不同的 id。insertAnyData 用于插入 student_reg,insert Any 用于插入剩余的表。我做错了什么或我错过了什么。这是我的代码

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;
}
4

0 回答 0