INSERT INTO后立即用AI获取PK列

时间:2016-08-02 15:44:54

标签: php mysql mysqli

在数据验证之后,在Customers表中填充行的SQL查询就像这样

mysqli_query($connect, "INSERT INTO Customers (CustFirst, CustLast, CustAddress) 
VALUES ('$CustFirst', '$CustLast', '$CustAddress')")

现在可行,非常直接,但Customers表有4列,CustID是PK和AI。我是否必须按照

的方式进行新的查询
mysqli_query($connect, "SELECT CustID from Customers 
WHERE CustFirst='$CustFirst 
AND CustLast='$CustLast' 
AND CustAddress='$CustAddress')

只是为了检索插入表中的唯一行的CustID?还是有捷径?我想按照

的方式做点什么
echo "The Customer " . $CustFirst . " " . $CustLast . " was added<br>";
echo "with " . $CustID . " being the number associated with the account.";

谢谢!

1 个答案:

答案 0 :(得分:1)

$CustID = mysqli_insert_id(connection);  

您可以在执行插入查询后立即编写上面的代码。这将返回数据库中插入的最新主键ID。