Reputation: 369
I am using simple MySQL code to insert data from a form with auto_increment id, it works fine on local host but not on server.
this is the code I am using
$myvar=$_POST['var'];
//Insert data into mysql table
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
in local host phpmyadmin data is inserted in table but on server phpmyadmin data is not inserted in table. In my localhost I am using XAMPP
whereas phpmyadmin on IIS server.
What setting should I do in phpmyadmin on server so that id is automatically inserted with auto increment, I know I can use mysql_insert_id()
to insert id but in lots of file i have used this type of code which I cannot change. I want the same setting as XAMPP
that can take this type of code easily.
Upvotes: 1
Views: 9322
Reputation: 6114
If you want the last of all the rows in the table, then this is finally the time where MAX(id)
is the right answer! :) kind of.
SELECT fields FROM mytable BY id DESC LIMIT 1;
will get the last id then increment it to 1 // add this value to id in insert statement
or if you have a autoincrement column change it to
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
to
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";
Upvotes: 1
Reputation: 214
if still you are getting the error
first check, in the server your id column must marked as auto_increment.data type should be int. if it is ok then
insert into mytable(myvar) values('test');
and try to use prepared statements to avoid the sql injection. Thanks.
hope this may usefull for you.
Upvotes: 1
Reputation: 57105
auto increment inserts id itself so you don't need to pass it through code
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";
or you can do this
$sql="INSERT INTO mytable(id,myvar) VALUES (NULL,'$myvar')";
if you want want to manually insert id for some reason
$sql="INSERT INTO mytable(id,myvar) VALUES (10,'$myvar')";
Upvotes: 0
Reputation: 690
First check your table Structure Property by applying query:
desc mytable (or) show create table mytable.
Check auto increment property been set for column id.
If yes means don't need to pass id in insert query.
Just write a query as :-
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";
Upvotes: 0
Reputation: 57052
You as inserting '' into auto-increment id. just insert other fields and MySQL handles the auto-increment column.
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
should be
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";
Upvotes: 7