Internial
Internial

Reputation: 543

How do I find the last record my database table using PDO?

How can I execute this using PDO? I use MySQL for my database. I am trying to call the last infog_id.

$q = $conn->query("SELECT * FROM Infographic ORDER BY infog_id DESC LIMIT 1");
$q->fetchAll(); 

Upvotes: 4

Views: 8002

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35337

Similar to what Sean said, if you only need one column, don't get all of them.

$q = $conn->query("SELECT infog_id FROM Infographic ORDER BY infog_id DESC LIMIT 1");
$infog_id = $q->fetchColumn();

fetchColumn() by default retrieves the first column from the next available row, for this query, this will be infog_id.

If you actually want the whole row, use fetch().

$q = $conn->query("SELECT * FROM Infographic ORDER BY infog_id DESC LIMIT 1");
$row = $q->fetch();

fetch() returns the next available row, in this case, there is only one (LIMIT 1).

Upvotes: 7

Related Questions