无法从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>
答
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.
答
To retrieve the last id in the table you need:
SELECT id FROM registers ORDER BY ID DESC LIMIT 1