0

I am doing an ajax to write records into the db. The table has id,fullname. The id is set to primary and auto increment. Now without the id (8 in the below statement) the record is not written.

Below is the insert statement

$sql = 
   "INSERT INTO user 
   VALUES ('8','".$_POST['name']."','test4','test5','test6')";

Is it possible to write without the id?

vinculis
  • 475
  • 3
  • 19
X10nD
  • 21,638
  • 45
  • 111
  • 152
  • Any errors? It should be possible. By the way, you should take a look at [this thread](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection) about sql injection because your query is vulnerable. – j0k Nov 22 '12 at 08:28
  • if you have set it to auto_increment, try with null, like this, `insert into user values (null,'".$_POST['name']."','test4','test5','test6')` – Nikola Nov 22 '12 at 08:28
  • @Nikola why don't you post it as an answer? Since it is one :) – j0k Nov 22 '12 at 08:30

5 Answers5

1

Place NULL instead of '8', that will tell MYSQL to do default auto increment:

$sql="insert into user values (NULL,'".$_POST['name']."','test4','test5','test6')";

Other possibility is to rewrite your query to this from:

$sql="insert into user (field1, field2, field3, field4) values ('".$_POST['name']."','test4','test5','test6')";

In this case you didnt specify id as a column to be inserted, so MySQL will again do the default auto increment

Ivan Hušnjak
  • 3,493
  • 3
  • 20
  • 30
1

You can also omit the ID column in the query so that It automatically increments the ID Value

Chella
  • 1,561
  • 4
  • 23
  • 42
0

Yes it's totally possible but you need to specify which columns you are inserting into... for example:

$sql="insert into user (username, column2, column3, column4) values ('".$_POST['name']."','test4','test5','test6')";
Dale
  • 10,384
  • 21
  • 34
0

Try

$sql="insert into user values (NULL,'".$_POST['name']."','test4','test5','test6')";

or

$sql="insert into user(`field1`, `field2`, `field3`, `field4`) values ('".$_POST['name']."','test4','test5','test6')";
AdrianPop
  • 108
  • 2
  • 8
0

You can use DEFAULT or NULL instead of '8'

insert into user(DEFAULT, column1, column2, column3) VALUES (....
it2051229
  • 339
  • 3
  • 13