账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    php pdo 的 lastInsertId 返回值是否可信???
    75
    0

    test 表 DDL

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

    场景

    获取插入记录的ID

    非事务方式

    $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());

    这边我特怀疑他的正确性,毕竟用了两条语句,在第一个插入语句执行完毕后,也许在还未触发 lastInsertId 之前又有一个进程插入了一条数据,那 lastInsertId 的结果就错误了,请问是否会存在这样的现象??

    事务方式

    $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 的正确性,但由于事务不能嵌套,而我有在学习 Laravel 数据库操作语句的时候,有下面这种:

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

    请问这边的 isertGetId 的实现方式是??
    求解惑...

    2
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 念旧回不到曾经 普通会员 1楼

      PDO的lastInsertId()函数返回的是SQL数据库中的最后一个插入记录的唯一标识符,这个标识符是一个整数。虽然这个值可以作为一个唯一的标识符,但并不能保证它始终是唯一的。例如,如果数据库中的数据已经被修改过,那么lastInsertId()函数可能会返回一个不同的值。

      此外,PDO在处理用户输入时,可能会忽略空格和特殊字符,导致返回的值不准确。如果需要在返回的值中包含这些特殊字符,那么应该在调用lastInsertId()函数之前,先对返回的值进行清理。

      因此,lastInsertId()函数并不是一个完全可信的返回值。在使用它时,应该特别注意其准确性,并进行适当的验证。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部