Using Prepared Statement, how I return the id of the inserted row?

后端 未结 3 532
遥遥无期
遥遥无期 2020-12-03 04:23

I want retrieve the id of a inserted row in the database, but I don\'t know how to do this.

I tried to return using the SQL clause RETURNING id, but not

相关标签:
3条回答
  • 2020-12-03 04:45

    You need to use:

    $stmt = $db->prepare("SQL Query");
    $stmt->execute();
    $id = $db->lastInsertId();
    
    0 讨论(0)
  • 2020-12-03 04:51
    $newid = mysqli_insert_id($mysqli_db);
    

    $mysqli_db is your mysqli database connection. As far as I know it shouldn't matter on which way ou inserted the row (prepared statement or direct INSERT INTO). mysqli_insert_id() should return the id of the last inserted row using this db connection.

    The alternative is to make another query like SELECT LAST_INSERT_ID();.

    0 讨论(0)
  • 2020-12-03 05:12

    After calling the execute() method on the PreparedStatement, the id of the insert row will be in the insert_id attribute. Only read it.

    $pstm->execute();
    $pstm->insert_id;
    
    0 讨论(0)
提交回复
热议问题