1

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')");
Hardik Solanki
  • 3,153
  • 1
  • 17
  • 28
Mia
  • 47
  • 1
  • 1
  • 6

3 Answers3

3

use this after insert query

$last_row = mysqli_insert_id($con);
Bhavik
  • 495
  • 2
  • 10
0

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

Max
  • 913
  • 1
  • 7
  • 18
0

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;
Kevin Sijbers
  • 814
  • 7
  • 19