Cesar Cervantes Cesar Cervantes - 1 year ago 44
MySQL Question

Fetching PK column with AI immediately after INSERT INTO

After data verification, the sql query to populate a row in the Customers table goes something like this

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

Now that works, pretty straight forward, but the Customers table has 4 columns, CustID being the PK and AI. Do I have to make a new query along the lines of

mysqli_query($connect, "SELECT CustID from Customers
WHERE CustFirst='$CustFirst
AND CustLast='$CustLast'
AND CustAddress='$CustAddress')

just to retrieve the CustID of the only row being inserted into the table? Or is there a shortcut? I would like to do someting along the lines of

echo "The Customer " . $CustFirst . " " . $CustLast . " was added<br>";
echo "with " . $CustID . " being the number associated with the account.";


Answer Source
$CustID = mysqli_insert_id(connection);  

You can write above code just after executing your insert query. This will return latest primary key id inserted in your database.