1

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

peace_love
  • 6,229
  • 11
  • 69
  • 157

2 Answers2

7

Why not just

SELECT name, id FROM data ORDER BY id DESC LIMIT 1
e4c5
  • 52,766
  • 11
  • 101
  • 134
0

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)
kscherrer
  • 5,486
  • 2
  • 19
  • 59