将数据插入表中并立即选择行的ID号

I have a MYSQL table called 'Buyers'. I am taking form data and inserting it into the table on a page called insert.php.

Now, along with the column names for the form fields, I have an Auto-increment ID column in the table. What I want is; once I send the form data to the table, I want to then execute some SQL to get the ID number for the row into which I just inserted the data into.

E.g, I have the SQL:

INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]');

This will create a row in the 'Buyers' table with the data from form fields 'name', 'email' and 'job'.

This row will have an ID number generated by Auto Increment.

How, then, can I then select that exact ID number? Is there some way to select the most recent row in the table, since that is the row which contains the ID number I want?

SELECT x.*
  FROM messages x
  JOIN 
      ( SELECT from_id, MAX(time_sent) time_sent GROUP BY from_id ) y
    ON y.from_id = x.from_id 
   AND y.time_sent = x.time_sent;

The last part of this puzzle is left as an exercise for the reader.

Use mysql_insert_id() to retrive ID. More details - http://php.net/manual/en/function.mysql-insert-id.php

Mysqli : mysqli_insert_id()

<?php
mysqli_query($con,"INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]')");
$last_id = mysqli_insert_id($con); 
?>

PDO : PDO::lastInsertId()

<?php
$stmt = $con->prepare("INSERT INTO Buyers (name, email, job) VALUES (?,?,?)");
$stmt->bind_param("sss", $_POST['name'], $_POST['email'], $_POST['job']);
$stmt->execute();
$last_id = $con->lastInsertId();
?>

Assuming $con as connection.

Mysql : mysql_insert_id()

<?php
mysql_query("INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]')");
$last_id = mysql_insert_id(); 
?>

NOTE: [The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead ]