duanliaoyu8419 2017-01-05 09:05
浏览 50

将具有外键关系的值同时插入两个不同的表中? (MySQL的)

So I have 2 tables:

  • users with columns id (primary, auto_increment), username, password, person_id (foreign key)
  • people with columns id (primary, auto_increment), first_name, last_name

What I'm trying to do is when registering a new account have a new row inserted into people and then have a new row inserted into users with the people.id as foreign key users.person_id.

Right now I have 2 php functions that get executed right after eachother, firstly one with this query:

insert into people (first_name, last_name) values (:firstname, :lastname)

Secondly one with this query:

insert into users (username, password, person_id) values (:user, :pass, LAST_INSERT_ID())

All of this works fine except for the fact that last_insert_id() keeps giving value 0 instead of the id from the previous query. Is it maybe not possible to use last_insert_id() when using 2 separate queries? If so what would be the best way to go about it then?

This is my relevant php code:

//make new person
$newPerson = new PeopleManagement();
$pm = $newPerson->createNewPerson($_POST["firstName"], $_POST["lastName"]);

//make new user
$newUsr = new Authentication();
$ac = $newUsr->registerNewUser($_POST["user"], $_POST["pass"]);


public function registerNewUser ($user, $pass) {
    try {

        $dbm = new PDO(DBCONFIG::$db_conn, DBCONFIG::$db_user, DBCONFIG::$db_pass);
        $dbm->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbm->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);        

            hash = password_hash($pass, PASSWORD_DEFAULT);

            $sql = "insert into users (username, password, person_id) values (:user, :pass, LAST_INSERT_ID())";

            $stmt = $dbm->prepare($sql);
            $stmt->execute(array(
                ':user' => $user,
                ':pass' => $hash
            ));

            $dbm = null;

    } catch(PDOException $ex) {
        return "Could not connect to database";
    }
}

public function createNewPerson($firstName, $lastName) {

    $dbm = new PDO($this->dbConn, $this->dbUser, $this->dbPass);

    $sql = "insert into people (first_name, last_name) values (:firstname, :lastname)";

    $stmt = $dbm->prepare($sql);
    $stmt->execute(array(
        ':firstname' => $firstName,
        ':lastname' => $lastName
    ));

    $dbm = null;
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 AT89C51控制8位八段数码管显示时钟。
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 下图接收小电路,谁知道原理
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题