Output the last row inserted in MySQLi

MySQLi makes grabbing the last inserted row easy. After running your insert query, you can do this:

$id = $mysqli->insert_id;

Then, you can query for that row like this:

$result = $mysqli->query("SELECT * FROM table_name WHERE ID = {$id}");

And, fetch the result as an object:

$user = $result->fetch_object();

From there it’s a simple echo to output it to your page:

echo $user->user_name;

(Although, you’ll want to use htmlspecialchars or htmlentities to escape the output and prevent XSS attacks. But, we’ll save that for another day.)

Simple.

Anyway, in the newly released Module 3 of PHP 101, I show you how to build a fully-functioning PHP form that submits and retrieves data from your database… so you’ll learn how to do this with all the bells and whistles like prepared statements, input filtering, output escaping and more.

It’s a simple proposition…

If you want to master all the ins and outs of MySQL…

This is how you do it.

Right now, you can grab all three modules for just 27 buqs.

That’s 10 buqs off the regular.

Here’s the link

Later,

John


Originally published at John Morris.

Like what you read? Give John Morris a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.