Home >> FAQs/Tutorials >> MySQL Tutorials

MySQL Tutorial - Define the ID Column as Auto-Incremented

By: FYIcenter.com

(Continued from previous topic...)

How To Define the ID Column as Auto-Incremented?

Many tables require an ID column to assign a unique ID number for each row in the table. For example, if you have a table to hold forum member profiles, you need an ID number to identify each member. To allow MySQL server to automatically assign a new ID number for each new record, you can define the ID column with AUTO_INCREMENT and PRIMARY KEY attributes as shown in the following sample script:

<?php
  include "mysql_connection.php";

  $sql = "CREATE TABLE fyi_users ("
      . " id INTEGER NOT NULL AUTO_INCREMENT" 
      . ", name VARCHAR(80) NOT NULL"
      . ", email VARCHAR(80)"
      . ", time TIMESTAMP DEFAULT CURRENT_TIMESTAMP()"
      . ", PRIMARY KEY (id)"
      . ")";
  if (mysql_query($sql, $con)) {
    print("Table fyi_users created.\n");
  } else {
    print("Table creation failed.\n");
  }

  mysql_close($con); 
?>

If you run this script, a new table will be created with ID column defined as auto-increment. The sample script below inserts two records with ID values assigned by MySQL server:



If you run this script, you will get something like this:

1 rows inserted.
1 rows inserted.
1, John King, 2006-07-01 23:02:39
2, Nancy Greenberg, 2006-07-01 23:02:39

(Continued on next topic...)

  1. How To Create a New Table?
  2. How To Get the Number of Rows Selected or Affected by a SQL Statement?
  3. How To Insert Data into an Existing Table?
  4. How To Fix the INSERT Command Denied Error?
  5. How To Insert Multiple Rows with a SELECT Statement?
  6. What Is a Result Set Object?
  7. How To Query Tables and Loop through the Returning Rows?
  8. How To Break Query Output into Pages?
  9. How To Update Existing Rows in a Table?
  10. How To Delete Existing Rows in a Table?
  11. How To Quote Text Values in SQL Statements?
  12. How To Quote Date and Time Values in SQL Statements?
  13. How To Display a Past Time in Days, Hours and Minutes?
  14. How To Perform Key Word Search in Tables?
  15. How To Build WHERE Criteria with Web Form Search Fields?
  16. How To Query Multiple Tables Jointly?
  17. How To Define the ID Column as Auto-Incremented?
  18. How To Get the Last ID Assigned by MySQL?

MySQL Tutorials:

More...


Other Tutorials/FAQs:

More...


Related Resources:

More...


Selected Jobs:

More...