...

View Full Version : MySQL insert then select?



Loic
03-26-2009, 12:35 AM
Hi all, I just wanted to know if I was possible to create a row, then select it unique auto incremented key?

For example if I have a table with the fields ID FirstName, LastName, Age and I am creating a new row with empty values except for the ID (the unique key) which will be automatically created as it is auto incremented. How do I get the value ID?



<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO Persons (ID, FirstName, LastName, Age)
VALUES
(NULL, '', '', '')");

mysql_close($con);
?>

PappaJohn
03-26-2009, 12:50 AM
Yes, you can use mysql_insert_id() (http://dev.mysql.com/doc/refman/5.1/en/mysql-insert-id.html) to return the auto-increment id.

RomanTaylor
03-26-2009, 04:55 AM
SQL command:

ALTER TABLE your_table ADD id INT NOT NULL AUTO_INCREMENT FIRST
Change the red text to your table name.

Inigoesdr
03-26-2009, 05:15 AM
SQL command:

ALTER TABLE your_table ADD id INT NOT NULL AUTO_INCREMENT FIRST
Change the red text to your table name.

Thank you for your post, but the user stated they already have an auto_increment column. PappaJohn's answer is correct.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum