0

hi ther I use this mysqli code to insert in DB.

mail DB has an id AUTO_INCREMENT.

$sql = "INSERT INTO mail (".$sqlname.") VALUES (".$sqlValue.")";
        if (!($conn->query($sql) === TRUE)) 
        {
            echo 'false';
            return false;
        }
        else
             return $id; // return id of insereted record in table

Is there any way to return id in mail table realtime after insert?

I can call last ID by call another function....But it may gone wrong for high traffick insert to DB.

partiz
  • 1,206
  • 2
  • 13
  • 34

2 Answers2

2

Description:

When a new AUTO_INCREMENT value has been generated, you can also obtain it by executing a SELECT LAST_INSERT_ID() statement with mysql_query() and retrieving the value from the result set returned by the statement.

For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It is not changed by another client. It is not even changed if you update another AUTO_INCREMENT column with a nonmagic value (that is, a value that is not NULL and not 0). Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid. Each client will receive the last inserted ID for the last statement that client executed.

See detail here: https://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

Muhammad Muazzam
  • 2,810
  • 6
  • 33
  • 62
1

If you are using mysqli, you can do it with mysqli_insert_id:

return $conn->insert_id;

If you are using PDO, you can do it with lastInsertId:

return $conn->lastInsertId();
Federkun
  • 36,084
  • 8
  • 78
  • 90