dpepbjp126917 2018-07-05 09:25
浏览 39

使用PHP和MYSQL将last_insert_id()插入到不同的表中时使用不同的ID

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;
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度