我正在向MySQL中插入新数据,并且有一列名为“ bookingid”的列是主键并具有自动递增功能。插入数据后,我需要获取自动增量的编号,这是我的代码:
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);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO reservations (bookingdatetime, firstname, lastname, address)
VALUES (:bookingdatetime, :firstname, :lastname, :address)");
$stmt->bindParam(':bookingdatetime', $bookingdatetime);
$stmt->bindParam(':firstname', $fname);
$stmt->bindParam(':lastname', $lname);
$stmt->bindParam(':address', $address);
// insert a row
$stmt->execute();
echo "success! row id: ";
}catch(PDOException $e){
echo json_encode(array("title" => "Database Error", "body" => $e->getMessage()));
}
$conn = null;
我如何回显显示“成功!行ID:”的增量?谢谢!
您可以使用lastInsertId()
检索插入的最后一行:
lastInsertId()
请注意,$stmt->execute();
echo "success! row id: $stmt->lastInsertId()";
必须在事务中的lastInsertId()
之前被调用,否则它将返回commit()
。