我无法从pdo连接获取最后一个插入ID,它总是返回0.我没有解决方案请帮助我.我的函数getConnection();
function getConnection(){
$servername="localhost";
$username="mmjadmin";
$password="gfam";
try{
$conn = new PDO("mysql:host=$servername;dbname=mmjdb",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $conn;
}catch(PDOException $e){
echo "Connect to database fail " . $e->getMessage();
}}
Run Code Online (Sandbox Code Playgroud)
我调用此函数来执行其他函数以插入数据
function insertUser($username,$password){
$sql = "INSERT INTO T_Users(
username,
password,
regist_date,
update_date)
VALUES(
:username,
:password,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP)";
$stmt = getConnection()->prepare($sql);
$stmt->bindParam(':username',$username);
$stmt->bindParam(':password',$password);
$stmt->execute();
$userid = getConnection()->lastInsertId();
}
Run Code Online (Sandbox Code Playgroud)
我无法获取我插入的最后一个用户标识,即userid是autoincrement,它总是返回0.
当你打电话时,你也会创建一个新的连接getConnection().您应该存储连接并重新使用它:
function insertUser($username,$password){
$conn = getConnection();
$sql = "INSERT INTO T_Users(
username,
password,
regist_date,
update_date)
VALUES(
:username,
:password,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username',$username);
$stmt->bindParam(':password',$password);
$stmt->execute();
$userid = $conn->lastInsertId();
return $userId; // if needed
}
Run Code Online (Sandbox Code Playgroud)