Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Aug 2007
    Posts
    57
    Thanks
    4
    Thanked 0 Times in 0 Posts

    MySQL insert then select?

    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 Code:
    <?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);
    ?>

  • #2
    Senior Coder
    Join Date
    Apr 2007
    Location
    Quakertown PA USA
    Posts
    1,028
    Thanks
    1
    Thanked 125 Times in 123 Posts
    Yes, you can use mysql_insert_id() to return the auto-increment id.
    John

  • #3
    Regular Coder
    Join Date
    Mar 2009
    Location
    Troutdale, OR
    Posts
    145
    Thanks
    12
    Thanked 6 Times in 6 Posts
    SQL command:
    Code:
    ALTER TABLE your_table ADD id INT NOT NULL AUTO_INCREMENT FIRST
    Change the red text to your table name.

  • #4
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,642
    Thanks
    2
    Thanked 405 Times in 397 Posts
    Quote Originally Posted by RomanTaylor View Post
    SQL command:
    Code:
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •