douban2014 2019-07-04 12:31
浏览 88
已采纳

无法从html中的sql检索最后插入的id

i am trying to display some values from database to my html calling the last inserted id

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * from registers where id= LAST_INSERT_ID()";
$result = $conn->query($sql);

if (!empty($result) && $result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo " $row[firstname] ";
    }
} else {
    echo "0 results";
}

But when I am using this, the result is not being displayed, is there any problem with my code, how do I retrieve the last inserted id from sql?

</div>
  • 写回答

2条回答 默认 最新

  • doubengshao8872 2019-07-04 12:56
    关注

    try this query

    $sql = "SELECT * from registers ORDER BY ID DESC limit 1 ";
    

    it will give you only one result and this result will be the last inserted ID. But ID needs to be auto increment.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?