鍍金池/ 問答/PHP  數(shù)據(jù)庫  網(wǎng)絡(luò)安全/ php pdo 的 lastInsertId 返回值是否可信???

php pdo 的 lastInsertId 返回值是否可信???

test 表 DDL

create table test (
    id int primary key not null auto_increment , 
    name varchar(500)
)

場景

獲取插入記錄的ID

非事務(wù)方式

$pdo = new PDO('mysql:host=127.0.0.1;dbname=test' , 'root' , '123456');
$stmt = $pdo->prepare("inset into test (name) values (:name)");
$stmt->execute([
    ':name' => 'test'
]);

// 獲取剛插入記錄的id
var_dump($pdo->lastInsertId());

這邊我特懷疑他的正確性,畢竟用了兩條語句,在第一個插入語句執(zhí)行完畢后,也許在還未觸發(fā) lastInsertId 之前又有一個進程插入了一條數(shù)據(jù),那 lastInsertId 的結(jié)果就錯誤了,請問是否會存在這樣的現(xiàn)象??

事務(wù)方式

$pdo = new PDO('mysql:host=127.0.0.1;dbname=test' , 'root' , '123456');
$pdo->beginTransacation();

try {
    $stmt = $pdo->prepare("inset into test (name) values (:name)");
    $stmt->execute([
        ':name' => 'test'
    ]);
    
    // 獲取剛插入記錄的id
    var_dump($pdo->lastInsertId());
    $pdo->commit();
} catch() {
    $pdo->rollBack();
}

這邊能保證獲取的 id 的正確性,但由于事務(wù)不能嵌套,而我有在學(xué)習(xí) Laravel 數(shù)據(jù)庫操作語句的時候,有下面這種:

\DB::transaction(function(){
    \DB::table('test')->insertGetId([
        ':name' => 'test'
    ]);
});

請問這邊的 isertGetId 的實現(xiàn)方式是??
求解惑...

回答
編輯回答
囍槑
可以這樣測試
$pdo = new PDO('mysql:host=127.0.0.1;dbname=test' , 'root' , '123456');
$stmt = $pdo->prepare("inset into test (name) values (:name)");
$stmt->execute([
    ':name' => 'test'
]);
sleep(5);
// 獲取剛插入記錄的id
var_dump($pdo->lastInsertId());

另起一個進程插入一條數(shù)據(jù).

沒用過laravel ,看了下thinkphp5 的源碼
getLastInsID 使用的是PDO 的 lastInsertId

clipboard.png

$this->linkID PDO 當(dāng)前連接ID

也就是說通過這個ID獲取的自增ID是屬于當(dāng)前對象的最后一次插入值的ID
并不是簡單的獲取最后一條數(shù)據(jù)的ID。

2017年5月13日 10:34