Loading a sequential number to a form

Discussion in 'Databases' started by kezza2040, Sep 12, 2011.

  1. #1
    I have an existing form that sends data, including a manually entered sequential number, into a mysql table but I'd now like to progress the form so that the sequential number (which will be +1 of the previous entry) is automatically populated when the (php) form is opened. My thinking is to have the id number of the last entered form retrieved with a value of +1

    I have got to the point where I can retrieve the previous number using:
    $query="SELECT * FROM contacts ORDER BY id DESC LIMIT 1";
    but I'm at a loss how to them get the +1 added in.

    Any guidance would be much appreciated.

    I'm slowly teaching myself some VERY basic coding skills so type slowly!

    Cheers
     
    kezza2040, Sep 12, 2011 IP
  2. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #2
    $query="SELECT max(id) + 1 FROM contacts";

    would give you the number you want, but you can just add the select to the insert:

    $query="INSERT INTO contacts (... , id)
    SELECT "...", (SELECT Max(id) + 1 FROM contacts)
    FROM contacts LIMIT 1"

    should do it. (... is the other fields you're inserting.) Of course, that's the most inefficient way to do it. Your way, two statements, is the second least efficient way. The most efficient way is to make id an autonumber field (Autoincrement in MySQL). Then you don't insert anything into id at all, the database does that internally.
     
    Rukbat, Sep 13, 2011 IP
  3. Rising_Star

    Rising_Star Active Member

    Messages:
    39
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    63
    #3
    yeah, make the id field to auto increment
     
    Rising_Star, Sep 17, 2011 IP