This question already has an answer here:
I select the latest inserted id
from my mySQL database. I also want to select the appropriate name
to that latest id
.
$pdo = $db->query('SELECT *,MAX(id) AS latest FROM data');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
$id = $row["latest"];
$name = $row["name"];
}
The selecting of the id
is working well. But not the latest name
is selected, instead always the name
of the first row of my table is selected. It doesn't fit to the id
</div>
Why not just
SELECT name, id FROM data ORDER BY id DESC LIMIT 1
I wanted to write following answer but i have to confess that i find e4c5's answer better.
SELECT * FROM data where id = (SELECT max(id) FROM data)