PHP/MySQL 插入行然后获取'id'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/897356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:15:25  来源:igfitidea点击:

PHP/MySQL insert row then get 'id'

phpmysql

提问by Hintswen

The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.

当我插入一行时,我的表的“id”字段会自动增加。我想插入一行然后获取该 ID。

I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?

我会按照我说的那样做,但是有没有一种方法可以做到这一点而不必担心插入行和获取 id 之间的时间?

I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.

我知道我可以在数据库中查询与输入的信息相匹配的行,但是有很大的变化,会有重复,唯一的区别是 id。

回答by cletus

$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);

See mysqli_insert_id().

mysqli_insert_id()

Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id()already has this functionality.

不管你做什么,不要插入然后做一个“ SELECT MAX(id) FROM mytable”。就像你说的,这是一个竞争条件,没有必要。mysqli_insert_id()已经有这个功能了。

回答by soulmerge

The MySQL function LAST_INSERT_ID()does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.

MySQL 函数LAST_INSERT_ID()正是您所需要的:它检索在此会话期间插入的 id 。因此使用它是安全的,即使有其他进程(例如,其他人调用完全相同的脚本)将值插入到同一个表中。

The PHP function mysql_insert_id()does the same as calling SELECT LAST_INSERT_ID()with mysql_query().

PHP 函数的mysql_insert_id()作用SELECT LAST_INSERT_ID()与使用mysql_query().

回答by NaturalBornCamper

As to PHP's website, mysql_insert_id is now deprecated and we must use PDO. To do this with PDO, proceed as following:

对于 PHP 的网站,mysql_insert_id 现在已被弃用,我们必须使用 PDO。要使用 PDO 执行此操作,请执行以下操作:

$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute( array(':name' => 'Bob', ':city' => 'Montreal') );

echo $db->lastInsertId();

回答by Luke

As @NaturalBornCamper said, mysql_insert_id is now deprecatedand should notbe used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi(MySQL Improved) using mysqli_insert_id.

作为@NaturalBornCamper说,mysql_insert_id现在已经过时,应该不会被使用。现在的选项是使用 PDO 或 mysqli。NaturalBornCamper 在他的回答中解释了 PDO,所以我将展示如何使用mysqli_insert_id使用MySQLiMySQL 改进)来做到这一点

// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been 
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);

Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php

查看 PHP 文档以获取更多示例:http: //php.net/manual/en/mysqli.insert-id.php

回答by leMoisela

I just want to add a small detail concerning lastInsertId();

我只想添加一个关于的小细节lastInsertId()

When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.

当一次输入多行时,它不返回最后一个 Id,而是返回最后插入的集合的第一个 Id 。

Consider the following example

考虑下面的例子

$sql = 'INSERT INTO my_table (varNumb,userid) VALUES
     (1, :userid),
     (2, :userid)';
$sql->addNewNames = $db->prepare($sql);
addNewNames->execute(array(':userid' => $userid));

echo $db->lastInsertId();

What happens here is that I push in my_tabletwo new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.

这里发生的是我推入了my_table两个新行。表的 id 是自动递增的。在这里,对于同一个用户,我添加了两行不同的varNumb.

The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the lastrow, but the id of the first row that was added in the last request.

最后回显的值将等于行的 id where varNumb=1,这意味着不是最后一行的 id,而是最后一个请求中添加的第一行的 id。

回答by user1012181

An example.

一个例子。

    $query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
    $query_new = $databaseConnection->prepare($query_new);
    $query_new->bind_param('s', $_POST['coursename']);
    $query_new->execute();
    $course_id = $query_new->insert_id;
    $query_new->close();

The code line $course_id = $query_new->insert_id;will display the ID of the last inserted row. Hope this helps.

代码行将$course_id = $query_new->insert_id;显示最后插入行的 ID。希望这可以帮助。

回答by Murali

Try like this you can get the answer:

像这样尝试你可以得到答案:

<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");

// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);

mysqli_close($con);
?>

Have a look at following links:

看看以下链接:

http://www.w3schools.com/php/func_mysqli_insert_id.asp

http://www.w3schools.com/php/func_mysqli_insert_id.asp

http://php.net/manual/en/function.mysql-insert-id.php

http://php.net/manual/en/function.mysql-insert-id.php

Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0

另请注意,此扩展在 PHP 5.5 中已弃用,并在 PHP 7.0 中删除

回答by Yaseen Ahmed

I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php

我在上面的链接http://php.net/manual/en/function.mysql-insert-id.php 中找到了答案

The answer is:

答案是:

mysql_query("INSERT INTO tablename (columnname) values ('$value')");        
echo $Id=mysql_insert_id();

回答by uriateho

Try this... it worked for me!

试试这个……它对我有用!

$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
    if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    $msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    $msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

回答by neoSmith

Another possible answer will be:

另一个可能的答案是:

When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.

当您定义表时,它会包含列和数据。列 id 可以具有属性AUTO_INCREMENT

By this method, you don't have to worry about the id, it'll be made automatically.

通过这种方法,您不必担心id,它会自动生成

For example (taken from w3schools)

例如(取自w3schools

CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)

Hope this will be helpful for someone.

希望这对某人有帮助。

Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

编辑:这只是你定义如何生成自动ID的部分,创建后获取它,之前的答案是正确的。