마지막으로 삽입된 레코드 ID 가져오기
AUTO_INCREMENT 필드가 있는 테이블에 대해 INSERT 또는 UPDATE를 수행하면 마지막으로 삽입/업데이트된 레코드의 ID를 즉시 얻을 수 있다.
표준 SQL 쿼리
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 )
이런식으로 입력한다.
MySQLi 객체 지향
PHP
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); 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 . "
" . $conn->error; } $conn->close(); ?>
MySQLi 절차
PHP
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); 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 . "
" . mysqli_error($conn); } mysqli_close($conn); ?>
PDO
PHP
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; $conn->exec($sql); $last_id = $conn->lastInsertId(); echo "New record created successfully. Last inserted ID is: " . $last_id; } catch(PDOException $e) { echo $sql . "
" . $e->getMessage(); } $conn = null; ?>
참고
W3C School - PHP MySQL Get Last Inserted ID
W3C School - SQL Tutorial
W3C School - PHP Tryit Editor