【问题标题】:Using Prepared Statement, how I return the id of the inserted row?使用 Prepared Statement,我如何返回插入行的 id?
【发布时间】:2011-09-27 06:08:00
【问题描述】:

我想检索数据库中插入行的 id,但我不知道该怎么做。

我尝试使用 SQL 子句 RETURNING id 返回,但不起作用。

插入一行后如何返回id?

【问题讨论】:

    标签: php mysql mysqli prepared-statement


    【解决方案1】:

    在Prepared Statement上调用execute()方法后,插入行的id会在insert_id属性中。

    $pstm->execute();
    $pstm->insert_id;
    

    【讨论】:

    • 但它会为每次执行返回一个对应且唯一的 ID 吗? documentation 下的顶部评论说,如果您多次执行相同的准备好的语句,则应该使用 mysqli_connection->insert_id 而不是 mysqli_stmt->insert_id。想你可能知道这是否正确。
    • 这仅在我将主索引列设置为 AUTO_INCREMENT 后对我有用。
    • $pstm->insert_id 不包含id!
    【解决方案2】:
    $newid = mysqli_insert_id($mysqli_db);
    

    $mysqli_db 是你的 mysqli 数据库连接。据我所知,插入行的方式无关紧要(准备好的语句或直接INSERT INTO)。 mysqli_insert_id() 应该使用此数据库连接返回最后插入的行的 id。

    另一种方法是进行另一个查询,例如SELECT LAST_INSERT_ID();

    【讨论】:

    • 值得一提的是,这种方法也适用于事务(不太明显)。
    • 这适用于PreparedStatement?我得到了 id:$pstm->execute();,之后,insert_id 属性的 id 为:$mysqli->insert_id;
    【解决方案3】:

    你需要使用:

    $stmt = $db->prepare("SQL Query");
    $stmt->execute();
    $id = $db->lastInsertId();
    

    【讨论】:

    • 仅当您使用PDO 而不是MySQLi
    猜你喜欢
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 2016-10-29
    • 1970-01-01
    • 2014-10-23
    相关资源
    最近更新 更多