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

时间:2017-01-05 09:05:47

标签: php mysql database lastinsertid last-insert-id

所以我有两张桌子:

  • usersid(主要,auto_increment),usernamepasswordperson_id(外键)
  • id(主要,auto_increment),first_namelast_name
  • 的人

我尝试做的是,在注册新帐户时,在people中添加了新行,然后将新行插入userspeople.idusers.person_id外键last_insert_id()

现在我有2个php函数可以在彼此之后立即执行,首先是一个有这个查询的函数:

  

插入people(first_name,last_name)值(:firstname,   :名字)

其次是这个查询:

  

插入用户(用户名,密码,person_id)值(:user,   :pass,LAST_INSERT_ID())

除了0不断提供值last_insert_id()而不是前一个查询中的id之外,所有这一切都正常。在使用2个单独的查询时,是否可能无法使用//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; } ?如果是这样,那么最好的方法是什么呢?

这是我的相关php代码:

syscat.tables

0 个答案:

没有答案