Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP mySQL - Insert new record into table with auto-increment on primary key

Wondering if there is a shorthand version to insert a new record into a table that has the primary key enabled? (i.e. not having to include the key column in the query) Lets say the key column is called ID, and the other columns are Fname, Lname, and Website

$query = "INSERT INTO myTable VALUES ('Fname', 'Lname', 'Website')"; 
like image 320
JimmyJammed Avatar asked Sep 20 '11 21:09

JimmyJammed


People also ask

Can auto increment be a primary key?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How can I get auto increment value after insert?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.

Does MySQL auto increment primary key?

One of the important tasks while creating a table is setting the Primary Key. The Auto Increment feature allows you to set the MySQL Auto Increment Primary Key field. This automatically generates a sequence of unique numbers whenever a new row of data is inserted into the table.

How do I change my primary key to auto increment?

To change a primary key to auto_increment, you can use MODIFY command. Let us first create a table. Look at the above sample output, StudentId column has been changed to auto_increment.


1 Answers

Use the DEFAULT keyword:

$query = "INSERT INTO myTable VALUES (DEFAULT,'Fname', 'Lname', 'Website')"; 

Also, you can specify the columns, (which is better practice):

$query = "INSERT INTO myTable           (fname, lname, website)           VALUES           ('fname', 'lname', 'website')"; 

Reference:

  • http://dev.mysql.com/doc/refman/5.6/en/data-type-defaults.html
like image 130
regality Avatar answered Sep 17 '22 08:09

regality