【问题标题】:How do i get the id of a row after i stored procedure存储过程后如何获取行的ID
【发布时间】:2016-08-29 04:57:27
【问题描述】:

我刚刚执行了一个存储过程,它将航班信息插入到我的表中,我想在每次插入后获取 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。谁能给我一个明确的解释?

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

    mysqli_insert_id — 返回上次查询中使用的自动生成的 id

    mysqli_insert_id() 函数返回由对具有 AUTO_INCREMENT 属性的列的表的查询生成的 ID。如果最后一个查询不是 INSERT 或 UPDATE 语句,或者修改后的表没有具有 AUTO_INCREMENT 属性的列,则此函数将返回零。

    所以请检查您是否已将 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:我没有测试这段代码。希望工作

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 2017-07-18
    • 2014-06-23
    • 1970-01-01
    • 2017-03-05
    • 2020-11-25
    • 1970-01-01
    相关资源
    最近更新 更多