使用 PDO 在准备好插入后获取最后一个插入 ID [英] Get last insert id after a prepared insert with PDO

查看:26
本文介绍了使用 PDO 在准备好插入后获取最后一个插入 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个新项目中使用 PHP PDO 和 PostgreSQL.

I'm using PHP PDO with PostgreSQL for a new project.

给定以下函数,如何返回刚刚插入的行的 id?它现在看起来不起作用.

Given the following function, how can I return the id of the row just inserted? It doesn't work the way it looks now.

function adauga_administrator($detalii) {
    global $db;
    $ultima_logare = date('Y-m-d');

    $stmt = $db->prepare("INSERT INTO site_admins (sa_nume, sa_prenume, sa_user_name, sa_password, sa_email, sa_id_rol, sa_status, sa_ultima_logare) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bindParam(1, $detalii['nume']);
    $stmt->bindParam(2, $detalii['prenume']);
    $stmt->bindParam(3, $detalii['username']);
    $stmt->bindParam(4, md5(md5($detalii['parola'] . SIGURANTA_PAROLE) . SIGURANTA_PAROLE));
    $stmt->bindParam(5, $detalii['email']);
    $stmt->bindParam(6, $detalii['rol'], PDO::PARAM_INT);
    $stmt->bindParam(7, $detalii['status'], PDO::PARAM_INT);
    $stmt->bindParam(8, $ultima_logare);    
    $stmt->execute(); 

    $id = $db->lastInsertId();
    return $id;
}

推荐答案

来自手册:

返回最后插入的ID行,或序列中的最后一个值对象,取决于底层司机.例如,PDO_PGSQL()要求您指定一个名称名称的序列对象参数.

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. For example, PDO_PGSQL() requires you to specify the name of a sequence object for the name parameter.

它应该是这样的:

return $db->lastInsertId('yourIdColumn');

更新文档链接

这篇关于使用 PDO 在准备好插入后获取最后一个插入 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆