简体   繁体   English

MYSQL:SQL查询获取autoincrement字段的值

[英]MYSQL: SQL query to get the value of autoincrement field

I have a table. 我有一张桌子。 The primary key is id and its auto incremented. 主键是id ,其自动递增。 Now when I insert a new record, I need to get the id with which the record was updated. 现在,当我插入新记录时,我需要获取记录更新的id。 How can I do that? 我怎样才能做到这一点? If i use the query... 如果我使用查询...

select max(id) from table_name

...after executing I can get the id. ...执行后我可以获得id。 But can I be sure that its the id of the record that was just inserted? 但是,我可以确定它刚刚插入的记录的ID吗? Because many people will be using the app at same time. 因为很多人会同时使用该应用程序。

I am using php and mysql. 我正在使用php和mysql。

Can ayone provie me a sample code snippet in php with mysql? ayone可以在php中使用mysql为我提供示例代码片段吗?

If you want to find out what the newest ID from an auto increment column is, you just have to run the mysql_insert_id() function right after your insert query. 如果要查找自动增量列中的最新ID,您只需在插入查询后立即运行mysql_insert_id()函数。

Like so: 像这样:

//--connection already made to database
//--now run your INSERT query on the table
mysql_query("INSERT INTO table_name (foo_column) VALUES ('everlong')");

//-- right after that previous query, you run this
$newest_id = mysql_insert_id();

And now $newest_id will contain the ID of the latest row inserted. 现在$newest_id将包含插入的最新行的ID。

假设您正在使用MySQLi PHP扩展,您需要的命令是mysqli_insert_id

In SQL you can do this 在SQL中,您可以执行此操作

SELECT LAST_INSERT_ID() 

In php you can call mysql_insert_id() 在php中你可以调用mysql_insert_id()

Using the same connection, run this query next: 使用相同的连接,然后运行此查询:

SELECT LAST_INSERT_ID()

Your database driver may have a convenience function for that. 您的数据库驱动程序可能具有便利功能。

Read the docs. 阅读文档。

you can use this to get the value of the next auto_increment value (given that you already connected to the server and selected the db; 您可以使用它来获取下一个auto_increment值的值(假设您已连接到服务器并选择了db;

$query = "SHOW TABLE STATUS LIKE 'tbl_name'";
$result = mysql_query($query);
$auto_incr_val = mysql_result($result, 0, 'Auto_increment');
echo $auto_incr_val;

This will give you the value that will be used next in the auto_increment column. 这将为您提供auto_increment列中接下来将使用的值。 EDIT: I'm sorry.. That wasn't your question.... 编辑:对不起..那不是你的问题....

Here is example in PHP: 以下是PHP中的示例:

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("YOUR QUERY HERE", $link);
$inserted_id = mysql_insert_id($link));

Query 询问

show create table

contains information you need in last string 包含最后一个字符串中需要的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM