PHP MySQL:  INSERT data and return primary key

detox1978
detox1978 used Ask the Experts™
on
Hi All,

I know how to insert data into a MySQL table using PHP, but how do i get the primary key back?


many thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Assuming the primary key is an auto-incrementing field, you'd do the following:

<pre>
   // With the mysql extention
   $value = mysql_insert_id();

  // With mysqli extention
  $value =  $mysqli->insert_id();
</pre>

Author

Commented:
Yes the primary key is an auto-incrementing field.

How does that link into my code?


$query = "INSERT INTO users (email) VALUES ('".$email."');";
mysql_query($query) or die("Could not update data");


the table 

Open in new window

Commented:
$value = mysql_insert_id();


just put that on line 3, and you'll have the auto-incremented value. ('i'm new here, I don't know how to get something to be marked as code). mysql_insert_id will grab the id of the last executed insert, so you want to use it right after the query, so you don't accidently perform another query and get the wrong value.

Author

Commented:
thanks will give it a try now.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial