Getting last id PDO

573 views Asked by At

This is what i have:

$stmt = $handler->prepare('SELECT id FROM users');
$stmt->execute();
$id = $handler->lastInsertId();

echo $id;

So, i want result to be for example "There is $id registered users".

2

There are 2 answers

1
Your Common Sense On BEST ANSWER

You never need to select the "last id" from a table. Every time you think you you need it, you need something else. For example, whatever "Last id" has nothing to do with the number of users registered. Instead, you have to count users:

$count = $handler->query('SELECT count(id) FROM users')->fetchColumn();
echo "There is $count registered users";
2
Gerard Roche On

PDO::lastInsertId -- Returns the ID of the last inserted row or sequence value.
https://secure.php.net/manual/en/pdo.lastinsertid.php.

What you want is a count of registered users, see Row count with PDO.

To retrieve the last inserted ID or sequence value see PDO get the last ID inserted.