我無法從pdo連接獲取最後一個插入ID,它總是返回0.我沒有解決方案請幫助我。 my function getConnection();PDO :: last插入ID總是返回0使用MYSQL並準備語句
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();
}}
我調用這個函數來對其他功能做數據插入到
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();
}
我不能讓我插入的用戶ID是自動增量的最後一個用戶ID,它總是返回0。
它現在工作,令人難以置信的是,這樣做。你能解釋我嗎?因爲它看起來像你的代碼和我的代碼一樣。 –
我在答案中解釋了它。不要多次調用'getConnection()'。如果有幫助,請接受我的回答:stackoverflow.com/help/someone-answers –