Collections:
Define the ID Column as Auto-Incremented in MySQL
How To Define the ID Column as Auto-Incremented in MySQL?
✍: FYIcenter.com
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:
<?php include "mysql_connection.php"; $sql = "INSERT INTO fyi_users (name)" . " VALUES ('John King')"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows inserted.\n"); } else { print("SQL statement failed.\n"); } $sql = "INSERT INTO fyi_users (name)" . " VALUES ('Nancy Greenberg')"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows inserted.\n"); } else { print("SQL statement failed.\n"); } $sql = "SELECT id, name, time FROM fyi_users"; $rs = mysql_query($sql, $con); while ($row = mysql_fetch_assoc($rs)) { print($row['id'].", ".$row['name'].", " . $row['time']."\n"); } mysql_free_result($rs); mysql_close($con); ?>
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
⇒ Retrieving the Last Sequence ID in MySQL
⇐ Query Multiple Tables Jointly in MySQL
2017-09-12, 1592🔥, 0💬
Popular Posts:
How To Recover a Dropped Index in Oracle? If you have the recycle bin feature turned on, dropped ind...
How To Enter Unicode Character String Literals in SQL Server Transact-SQL? Unicode characters are mu...
What is sqlservr.exe - Process - SQL Server (SQLEX?PRESS) in SQL Server? Process sqlservr.exe is the...
Where to find answers to frequently asked questions on Downloading and Installing SQL Server 2005 Ex...
How To Drop an Index in Oracle? If you don't need an existing index any more, you should delete it w...