简体   繁体   English

如何从插入的数据中获取最后一个ID?

[英]How do i get the last ID's from the inserted data?

I have an option to send multiple rows into an table, i'm using an foreach to do that: 我可以选择将多个行发送到一个表中,我正在使用一个foreach来做到这一点:

if (is_array($add['jobname'])) {
$insert = "INSERT INTO job_offers (job_category, status) VALUES ";

foreach ($add['job_name'] as $key => $value) {

$insertedval[] = "
('" . safe($add['job_category'][$key]) . "', 
 '" . safe($add['status'][$key]) . "')";

}
}
$insert .= implode($insertedval, ",");

$last_id = db_query($insert, '+id?'); //gets the last generated ID, its a function that i created, and working great.

The problem is that i want to get the last ID, and i'm getting, but i'm inserting multiple rows into the database, and i want to get the ID's from all the inserted values, because they are being sent at the same time. 问题是我想获取最后一个ID,但我正在向数据库中插入多行,并且我想从所有插入的值中获取ID,因为它们是在同一时间发送的时间。

I can't put the $last_id variable inside the foreach loop, what do i do? 我无法将$ last_id变量放入foreach循环内,该怎么办?

ps: i'm using auto increment ps:我正在使用自动递增

Can you try something like this? 你可以尝试这样的事情吗?

$db = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");
$db->beginTransaction();
$stmt = $db->prepare('INSERT INTO job_offers (job_category, status) VALUES (?, ?)');

$insertedIds = array();
foreach ($add['job_name'] as $key => $value) {
    $stmt->execute($add['job_category'][$key], $add['status'][$key]));
    $id = $db->lastInsertId();
    array_push($insertedIds, $id);
}

$db->commit();

the ids should be in the insertedIds. 这些ID应该在insertIds中。

You can't. 你不能

Only by saving the the last index id before the inserted data, and than do it again after and select all the ids between that range. 仅通过保存插入数据之前的最后一个索引ID,然后再保存并选择该范围之间的所有ID,才可以。

SELECT ID FROM job_offers ID BETWEEN last-before-insert AND last-after-insert

You don't need a custom function to get the last insert id , there is already one built into both php mysqli and php PDO extensions . 您不需要自定义函数即可获取最后一个插入ID,php mysqli和php PDO扩展中已经内置了一个。

As far I know , the last insert id is session aware , meaning you will get the last insert from the current insert requests only . 据我所知,最后一个插入ID是会话感知的,这意味着您将仅从当前插入请求中获取最后一个插入。

Get last inset id using PHP PDO 使用PHP PDO获取最后的插图ID

$pdo->lastInsertId();

Get last insert id using mysqli 使用mysqli获取最后的插入ID

$mysqli->insert_id;

$pdo and $mysqli are the connection variables $ pdo和$ mysqli是连接变量

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

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