0

If I have a table named MUSIC:

ID   SONG   ARTIST
1    Gum    Tim
2    Air    Bob

How can I insert a row with autoincrement ID?

INSERT INTO MUSIC (ID, SONG, ARTIST)
VALUES (,earth, mark);
1
  • What does PHP have to do with this question? What do you want to do in PHP? Auto-increment is controlled by the database. Commented Dec 14, 2011 at 21:04

5 Answers 5

1

As long as ID is your autoincrement this should work. You don't need to declare it in your field listing.

INSERT INTO MUSIC (SONG, ARTIST) VALUES (earth, mark);
Sign up to request clarification or add additional context in comments.

2 Comments

well I was writing the codes in a php page.. i was adding the ID in the insert field that was my error..... that solved the problm..!! thanks!! :)
Please be sure to accept the answer that fixed your problem whether this one or another in the thread. high acceptance rating ensures you will be helped more often.
1

You could either do:

INSERT INTO MUSIC (SONG, ARTIST) VALUES ('earth', 'mark');

or

INSERT INTO MUSIC (ID, SONG, ARTIST) VALUES (NULL, 'earth', 'mark');

Comments

0

ID field should be "autoincrement", read more here

And in case it's already autoincroment:

INSERT INTO MUSIC (SONG, ARTIST) VALUES ('Yesterday', 'Beatles');

Comments

0

You don't need to use autoincrement ID in the SQL. Use this

INSERT INTO MUSIC (SONG, ARTIST) VALUES (earth, mark);

instead, ID column will populate automatically...

Comments

-1

You'll have to set the table in sql to have a primary key. It isn't PHP's job to create the key. Then, if you need the primary key, do something like this:

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>

Source: http://php.net/manual/en/function.mysql-insert-id.php

1 Comment

-1, please stop spreading the use of the mysql extension. Please encourage the use of mysqli or PDO instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.