MySQL获取主键后插入统计 [英] MySQL get Primary Key after Insert Statment
本文介绍了MySQL获取主键后插入统计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用以下insert语句,并且主键字段是自动递增。我需要在插入后返回新的主键值。最好使用一个语句来执行插入和返回主键值。
$ query = $ database-> connection-> prepare(INSERT INTO accounts(created,priviledge,password,token,idle)VALUE('$ created','1',:password,'$ token_encrypt','$ idle')
$ query-> bindParam(:password,$ password_hash);
$ query-> execute();
解决方案
使用
$ database-> connection-> lastInsertId()
pre>
并确保返回当前会话的值。所以从评论中回答您的问题 - 没有机会从并发会话中得到错误的值。
I need to use the following insert statement, and the primary key field is auto increment. I need to return the new primary key value after the insert. Preferably using one statement to do the insert and return primary key value.
$query = $database->connection->prepare("INSERT INTO accounts (created, priviledge, password, token, idle) VALUE ('$created', '1', :password, '$token_encrypt', '$idle')"); $query->bindParam(":password", $password_hash); $query->execute();
解决方案As soon as you're using PDO you need to use
$database->connection->lastInsertId()
And it guarantees you to return the value from the current session. So answering to your question from comments - there is no chance you get the wrong value from a concurrent session.
这篇关于MySQL获取主键后插入统计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文