我尝试使用以下代码:
$last_id = Connection::connect() -> lastInsertId('name');
以获取最后插入的项的id,但该项不起作用。有人可以帮助确定问题吗?
<?php
class Connection{
static public function connect(){
$link = new PDO("mysql:host=localhost;dbname=ham", "root", "");
$link -> exec("set names utf8");
return $link;
}
}
static public function mdlAddAccount($tableOne, $dataOne, $tableTwo, $dataTwo){
$stmtTwo = Connection::connect() ->prepare("INSERT INTO $tableTwo(name, planLevel) VALUES (:name, :planLevel)");
$stmtTwo -> bindParam(":name", $dataTwo["name"], PDO::PARAM_STR);
$stmtTwo -> bindParam(":planLevel", $dataTwo["planLevel"], PDO::PARAM_STR);
$last_id = Connection::connect() -> lastInsertId('name');
$stmtOne = Connection::connect()->prepare("INSERT INTO $tableOne(name, user, password, profile, status, relatedAccountID) VALUES (:name, :user, :password, :profile, :status, :relatedAccountID)");
$stmtOne -> bindParam(":name", $dataOne["name"], PDO::PARAM_STR);
$stmtOne -> bindParam(":user", $dataOne["user"], PDO::PARAM_STR);
$stmtOne -> bindParam(":password", $dataOne["password"], PDO::PARAM_STR);
$stmtOne -> bindParam(":profile", $dataOne["profile"], PDO::PARAM_STR);
$stmtOne -> bindParam(":status", $dataOne["status"], PDO::PARAM_STR);
$stmtOne -> bindParam(":relatedAccountID", $last_id, PDO::PARAM_STR);
#$stmt -> bindParam(":photo", $data["photo"], PDO::PARAM_STR)
if ($stmtOne->execute() && $stmtTwo->execute()) {
return 'ok';
} else {
return 'error';
}
$stmt -> close();
$stmt = null;
}
您必须在执行插入的同一连接上调用lastInsertId()
。这样可以确保它返回您插入的同一行的ID,而不是同时由另一个连接插入的内容。
因此,您不应该每次调用connect()
时都创建新的连接。它应该保存连接并重复使用。
class Connection{
static $conn = null;
static public function connect(){
if (self::$conn) {
return self::$conn;
}
$link = new PDO("mysql:host=localhost;dbname=ham", "root", "");
$link -> exec("set names utf8");
self::$conn = $link;
return $link;
}
}
您需要在执行INSERT
查询后获得插入ID,而不是在准备它之后。因此,不能在同一if
条件下同时执行这两个查询。
if ($stmtTwo->execute()) {
$last_id = Connection::connect() -> lastInsertId('name');
if ($stmtOne->execute()) {
return 'ok';
} else {
return 'error';
}
} else {
return 'error';
}
请注意,您实际上不需要在此处使用lastInsertId()
。这相当于MySQL内置的函数LAST_INSERT_ID()
,您可以将其放入SQL本身。
$stmtOne = Connection::connect()->prepare("
INSERT INTO $tableOne(name, user, password, profile, status, relatedAccountID) VALUES
(:name, :user, :password, :profile, :status, LAST_INSERT_ID())");
然后,您需要按照正确的顺序执行查询。&&
从左到右计算其参数,因此$stmtTwo->execute()
必须排在第一位(变量名向后(。
if ($stmtTwo->execute() && $stmtOne->execute()) {
return 'ok';
} else {
return 'error';
}