Mia
Mia

Reputation: 47

get the id of the last inserted row in mysql

I have looked everywhere and keep getting different answers and incorrect code. All I want to do is after I have added a field to my database in MySQL is to get the user_id of the field that has just been created. I just cannot seem to do it?

I am using this to input the field and thanks for any help. It has a auto_increment value of user_id which is what I need to get.

mysqli_query($con,"INSERT INTO users_accounts (business, email_uniq)
VALUES ('$business', '$email_uniq')");

Upvotes: 1

Views: 2622

Answers (3)

Kevin Sijbers
Kevin Sijbers

Reputation: 824

After executing the query, you can use mysqli::$insert_id value or mysqli_insert_id function to retrieve the last generated id, like this:

mysqli_query($con,"INSERT INTO users_accounts (business, email_uniq) VALUES ('$business', '$email_uniq')");
$insert_id = mysqli_insert_id($con);

or using the object functions:

$con->query("INSERT INTO users_accounts (business, email_uniq) VALUES ('$business', '$email_uniq')");
$insert_id = $con->insert_id;

edit: Not related, but definitly important! If the values for either of these parameters $business or $email_uniq are user supplied, it is highly recommended to make sure they are filtered properly. The easiest way is by using a prepared statement for security (http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Here is your code using prepared statements:

$stmt = $con->prepare("INSERT INTO users_accounts (business, email_uniq) VALUES (?,?)");
$stmt->bind_param("ss", $business, $email_uniq);
$stmt->execute();
$insert_id = $con->insert_id;

Upvotes: 0

Max
Max

Reputation: 1013

You can return the primary key of the last row inserted with

$last_id = mysqli_insert_id($con);

You can find more information here: http://php.net/manual/en/mysqli.insert-id.php

Upvotes: 0

Bhavik
Bhavik

Reputation: 503

use this after insert query

$last_row = mysqli_insert_id($con);

Upvotes: 3

Related Questions