Which is correct way to get last inserted id in my

2019-05-02 00:50发布

问题:

i am using mysqli prepared statement to insert record in the table like this

$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
mysqli_stmt_execute($stmt);

if(mysqli_stmt_affected_rows($stmt) > 0){
//if insert is successful then get the insrted id.


}

/* close statement and connection */
mysqli_stmt_close($stmt);

/* close connection */
mysqli_close($link);

and would like to get the last inserted id , as the table has record_num field which is auto increment .

so my question is should i place connection name or the statement name inside the function.

i.e 1)

echo mysqli_insert_id($link);

Source: http://php.net/manual/en/mysqli.insert-id.php

2)

echo mysqli_stmt_insert_id($stmt);

Source: http://php.net/manual/en/mysqli-stmt.insert-id.php

which one is correct ? which one will give me last insrted id by the $stmt ?

  • there are no other inserts are being done using the same stmt one the same page..*

Update:

according to the note from http://php.net/manual/en/mysqli-stmt.insert-id.php

I am doing only single insert so i guess i can use

mysqli_stmt_insert_id($stmt)

but while doing multiple inserts using prepared statements using

echo mysqli_insert_id($link);

is best practice.

回答1:

You should use

mysqli_insert_id($link);

Because of this note on the PHP manual you referred us to

mysqli_stmt_insert_id

It should be noted that using mysqli_stmt->insert_id will not result in a unique ID being returned for each execution of a prepared insert statement. In practice, it appears that the first insertion ID is returned. If you are performing multiple inserts with the same prepared statement (one invocation of mysqli_stmt::prepare and multiple invocations of mysqli_stmt::execute() for a given statement), and need to keep the unique ID for each insert, use mysqli_connection->insert_id.



回答2:

for procedural language you need to use below code, mysqli_insert_id($link));

yes as you mention in 1 point.



回答3:

Correct is 1) - link, as stated in documentation:

http://php.net/manual/en/mysqli.insert-id.php