例
您可能经常发现需要获取刚刚插入到数据库表中的行的自动递增 ID 值。您可以使用最后一个插入 Id() 方法实现此目的。
// 1. Basic connection opening (for MySQL)
$host = 'localhost';
$database = 'foo';
$user = 'root'
$password = '';
$dsn = "mysql:host=$host;dbname=$database;charset=utf8";
$pdo = new PDO($dsn, $user, $password);
// 2. Inserting an entry in the hypothetical table 'foo_user'
$query = "INSERT INTO foo_user(pseudo, email) VALUES ('anonymous', 'anonymous@example.com')";
$query_success = $pdo->query($query);
// 3. Retrieving the last inserted id
$id = $pdo->lastInsertId(); // return value is an integer
在 postgresql 和oracle中,有 RETURN 关键字,它返回当前插入/修改的行的指定列。下面是插入一个条目的示例:
// 1. Basic connection opening (for PGSQL)
$host = 'localhost';
$database = 'foo';
$user = 'root'
$password = '';
$dsn = "pgsql:host=$host;dbname=$database;charset=utf8";
$pdo = new PDO($dsn, $user, $password);
// 2. Inserting an entry in the hypothetical table 'foo_user'
$query = "INSERT INTO foo_user(pseudo, email) VALUES ('anonymous', 'anonymous@example.com') RETURNING id";
$statement = $pdo->query($query);
// 3. Retrieving the last inserted id
$id = $statement->fetchColumn(); // return the value of the id column of the new row in foo_user