PHP MYSQL - Insert into without using column names but with autoincrement field

PhpMysqlAuto Increment

Php Problem Overview


I need to insert a long row with 32 fields into a MySQL table.

I'd like to do something like this:

$sql="insert into tblname values (... 32 fields ...)";

Obviously it works fine if the fields are in the same order as the MySQL table fields. But, my table has an auto-increment id as it's first field.

What I want is to fill in all table names but the first (id) one.

Suggestions?

Php Solutions


Solution 1 - Php

Just use NULL as your first value, the autoincrement field will still work as expected:

INSERT INTO tblname VALUES (NULL, ... 32 Fields ... )

Solution 2 - Php

Insert NULL into the auto-increment field.

I recommend that unless this is a hack script, you use field names. The rationale is that your code will break if you ever add a field to the table or change their order.

Instead, be explicit with field names, and it will go much better in the future.

Solution 3 - Php

We should omit any column values when we try without column name in insert query,

Advise if above information is wrong.

Solution 4 - Php

Here's a great shortcut that I've used (courtesy of a friend who wrote it for me)

$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
 $fieldlist.=$key.',';
 $vallist.='\''.urlencode($value).'\','; }
$fieldlist=substr($fieldlist, 0, -1);
$vallist=substr($vallist, 0, -1);
$sql='INSERT INTO customer_info ('.$fieldlist.') VALUES ('.$vallist.')'; 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaulo BuenoView Question on Stackoverflow
Solution 1 - PhpDoug NeinerView Answer on Stackoverflow
Solution 2 - PhpgahooaView Answer on Stackoverflow
Solution 3 - Phpbharanikumar BsView Answer on Stackoverflow
Solution 4 - PhpChaya CooperView Answer on Stackoverflow