gpt4 book ai didi

php - 我如何在存储过程后获取行的 ID

转载 作者:可可西里 更新时间:2023-11-01 07:34:18 28 4
gpt4 key购买 nike

我刚刚执行了一个将航类信息插入到我的表中的存储过程,我想在每次插入后获取 ID。但是我找不到其他适合我的方法。我想获取 auto_increment 上的 flight_id。

mysqli_query($conn,"CALL addschedule('$airlineID','$from','$to','$departDate','$arriveDate','$departTime','$arrivalTime','$price')");

$last_id = mysqli_insert_id($conn);
echo $last_id;

运行 mysqli_insert_id 只返回 0 值,但我最后的航类 ID 是 3。谁能给我一个明确的解释?

最佳答案

mysqli_insert_id — Returns the auto generated id used in the last query

The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

因此请检查您是否已将 AUTO_INCREMENT 属性设置为您的 id 字段。

或者如果您将其设置为 AUTO_INCREMENT。此示例代码可能对您有所帮助。

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");


$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

/* In op's case
mysqli->query($conn,"CALL addschedule('$airlineID','$from','$to','$departDate','$arriveDate','$departTime','$arrivalTime','$price')");
*/

printf ("New Record has id %d.\n", $mysqli->insert_id);


/* close connection */
$mysqli->close();
?>

答案 2

在你的 SP 中

INSERT INTO table VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000);
select LAST_INSERT_ID();

在你的 php 代码中

$result=mysqli_query($conn,"CALL addschedule('$airlineID','$from','$to','$departDate','$arriveDate','$departTime','$arrivalTime','$price')");

echo "Last ID: ".$result;

这可能会完成您的工作。

PS:我没有测试这段代码。希望工作

关于php - 我如何在存储过程后获取行的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39198722/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com