简体   繁体   English

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

[英]PHP/MySQL insert row then get 'id'

The 'id' field of my table auto increases when I insert a row.当我插入一行时,我的表的“id”字段会自动增加。 I want to insert a row and then get that 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。

$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 ".无论您做什么,都不要插入然后执行“ 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. mysqli_insert_id()已经有这个功能。


Another way would be to run both queries in one go, and using MySQL 's LAST_INSERT_ID() method, where both tables get modified at once (and PHP does not need any ID), like:另一种方法是同时运行两个查询,并使用MySQLLAST_INSERT_ID()方法,其中两个表都被一次修改(并且 PHP 不需要任何 ID),例如:

mysqli_query($link, "INSERT INTO my_user_table ...;
  INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");

Note that Each connection keeps track of ID separately (so, conflicts are prevented already).请注意,每个连接都单独跟踪 ID(因此,已经防止了冲突)。

The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session . MySQL 函数LAST_INSERT_ID()正是您所需要的:它检索在此会话期间插入的 id。 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.因此使用它是安全的,即使有其他进程(例如,其他人调用完全相同的脚本)将值插入到同一个表中。

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()调用SELECT LAST_INSERT_ID()的作用相同。

As to PHP's website, mysql_insert_id is now deprecated and we must use either PDO or MySQLi (See @Luke's answer for MySQLi).至于 PHP 的网站,mysql_insert_id 现已弃用,我们必须使用PDOMySQLi (请参阅 @Luke 对 MySQLi的回答)。 To do this with PDO, proceed as following:要使用 PDO 执行此操作,请执行以下操作:

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

echo $db->lastInsertId();

As @NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used.作为@NaturalBornCamper说, mysql_insert_id现在已经过时应该被使用。 The options are now to use either PDO or mysqli.现在的选项是使用 PDO 或 mysqli。 NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi ( MySQL Improved ) using mysqli_insert_id . 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

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_table two new rows.这里发生的是我将my_table推入了两个新行。 The id of the table is auto-increment.表的 id 是自动递增的。 Here, for the same user, I add two rows with a different varNumb .在这里,对于同一个用户,我添加了具有不同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 last row, but the id of the first row that was added in the last request.最后回显的值将等于varNumb=1所在行的 id,这意味着不是最后一行的 id,而是最后一个请求中添加的第一行的 id。

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;代码行$course_id = $query_new->insert_id; will display the ID of the last inserted row.将显示最后插入的行的 ID。 Hope this helps.希望这可以帮助。

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 中删除

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();

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);
    }

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的部分,创建后获取它,之前的答案是正确的。

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

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