Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

php - Get last insert id after a prepared insert with PDO

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the Manual:

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.

It should be something like:

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

[EDIT] Update link to doc


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...