Latest web development tutorials

PHP mysqli_insert_id () function

PHP MySQLi Reference Manual PHP MySQLi Reference Manual

Suppose websites table has an auto-generated ID field. Returns the last query ID:

<?php 
// 假定数据库用户名:root,密码:123456,数据库:w3big 
$con=mysqli_connect("localhost","root","123456","w3big"); 
if (mysqli_connect_errno($con)) 
{ 
    echo "连接 MySQL 失败: " . mysqli_connect_error(); 
} 

mysqli_query($con,"INSERT INTO websites (name,url,alexa) 
VALUES ('本教程','http://www.w3big.com',5633)");

// 输出自动生成的 ID
echo "新 id 为: " . mysqli_insert_id($con); 

mysqli_close($con);
?>

Definition and Usage

mysqli_insert_id () function returns the last query is automatically generated ID (generated by AUTO_INCREMENT).


grammar

mysqli_insert_id( connection ) ;

参数 描述
connection 必需。规定要使用的 MySQL 连接。

technical details

return value: Returns the integer value of a field with AUTO_INCREMENT automatically generated in the last query. If number> maximum integer value, it returns a string. If you do not update or no AUTO_INCREMENT field, returns 0.
PHP version: 5+


PHP MySQLi Reference Manual PHP MySQLi Reference Manual