轻松上手,快乐学习!

PHP 教程

PHP 教程PHP 简介PHP 下载安装PHP 语法PHP 注释PHP 变量PHP Echo / PrintPHP 数据类型PHP 字符串PHP 数值PHP MathPHP 常量PHP 运算符PHP If...ElsePHP SwitchPHP 循环While 循环Do While 循环For 循环Foreach 循环Break/ContinuePHP 函数PHP 数组索引数组关联数组多维数组数组排序PHP 全局变量$GLOBALS$_SERVER$_REQUEST$_POST$_GETPHP 正则表达式PHP 表单处理PHP 表单验证PHP 表单验证必填字段PHP 表单验证URL/E-mailPHP 表单验证实例PHP 日期和时间PHP IncludePHP 文件处理PHP 文件打开/读取PHP 文件创建/写入PHP 文件上传PHP CookiesPHP SessionsPHP FiltersPHP Filters AdvancedPHP 回调函数PHP JSONPHP 异常处理PHP 什么是 OOPPHP 类和对象PHP 构造函数PHP 析构函数PHP 访问修饰符PHP 继承PHP 类常量PHP 抽象类PHP 接口PHP 特征PHP 静态方法PHP 静态属性PHP 命名空间PHP 可迭代对象MySQL DatabaseMySQL ConnectMySQL Create DBMySQL Create TableMySQL Insert DataMySQL Get Last IDMySQL Insert MultipleMySQL PreparedMySQL Select DataMySQL WhereMySQL Order ByMySQL Delete DataMySQL Update DataMySQL Limit DataPHP XML ParsersPHP SimpleXML ParserPHP SimpleXML - GetPHP XML ExpatPHP XML DOMAJAX IntroAJAX PHPAJAX DatabaseAJAX XMLAJAX Live SearchAJAX PollPHP 实例PHP 编译器PHP 测验PHP 练习

PHP 参考手册

PHP 概述PHP ArrayPHP CalendarPHP DatePHP DirectoryPHP ErrorPHP ExceptionPHP FilesystemPHP FilterPHP FTPPHP JSONPHP KeywordsPHP LibxmlPHP MailPHP MathPHP MiscPHP MySQLiPHP NetworkPHP Output ControlPHP RegExPHP SimpleXMLPHP StreamPHP StringPHP Variable HandlingPHP XML ParserPHP ZipPHP Timezones


PHP MySQL 获取上次插入记录的 ID


获取上次插入记录的 ID

如果我们对具有自动增量字段的表执行插入或更新,我们可以立即获得上次插入/更新记录的ID。

在表 "MyGuests" 中,"id" 列是一个自动递增字段:

CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

以下示例与上一页中的示例相同,只是我们添加了一行代码来检索最后插入的记录的 ID。我们还回显最后插入的 ID:

实例 (MySQLi - 面向对象)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
  $last_id = $conn->insert_id;
  echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>


实例 (MySQLi - 面向过程)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
  $last_id = mysqli_insert_id($conn);
  echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
  echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

实例 (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $sql = "INSERT INTO MyGuests (firstname, lastname, email)
  VALUES ('John', 'Doe', 'john@example.com')";
  // use exec() because no results are returned
  $conn->exec($sql);
  $last_id = $conn->lastInsertId();
  echo "New record created successfully. Last inserted ID is: " . $last_id;
} catch(PDOException $e) {
  echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>