how to increment a variable inserted in database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • simon2x1
    New Member
    • Dec 2008
    • 123

    how to increment a variable inserted in database

    I want to increment the variable number when ever there is a insertion to the database for the first insertion it should be 001 the next person or insertion should be 002.

    Code:
    
    <?php
    
    $user =  ($_POST['person']);
    $number =  "001"; //what to increament these
    
    mysql_query("INSERT INTO users (person, user_num) VALUES ('$user','$number')") or die(mysql_error()); 
    ?>
  • yusuf ali bozki
    New Member
    • Dec 2010
    • 4

    #2
    very simple :)
    Code:
    $id = $_POST['person'];
    $sql = "Update users set user_num=+1 where person='$id' ";
    mysql_query($sql);

    Comment

    • Samishii23
      New Member
      • Sep 2009
      • 246

      #3
      Or you don't have to at all.
      MySQL has a built in auto increment feature.

      This snippet was taken from a PHPMyAdmin table creation
      Code:
      CREATE TABLE `test` (
        `id` INT( 3 ) NOT NULL AUTO_INCREMENT ,
        PRIMARY KEY (  `id` ) ,
        UNIQUE (`id`)
      )
      This, from a table update
      Code:
      ALTER TABLE  `testing` ADD UNIQUE (`id`)
      // Then ...
      ALTER TABLE  `testing` CHANGE  `id`  `id` INT( 5 ) NOT NULL AUTO_INCREMENT
      Its important the tables column is set to unique, as it is required for the auto feature. Also note, only one auto feature is allowed per table. You can more then one unique index, though you'd have to be careful of that you enter into that column.

      Every insert you make into that table with increment the ID value from my example. Just a side note, deleting table entrys doesn't effect the increment value.

      Comment

      Working...