PHP MYSQL - 插入不使用列名但使用自动增量字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1871331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:07:35  来源:igfitidea点击:

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

phpmysqlauto-increment

提问by Paulo Bueno

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

我需要在 MySQL 表中插入一个包含 32 个字段的长行。

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.

显然,如果字段与 MySQL 表字段的顺序相同,它就可以正常工作。但是,我的表有一个自动递增的 id,因为它是第一个字段。

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

我想要的是填写所有表名,但第一个(id)。

Suggestions?

建议?

回答by Doug Neiner

Just use NULLas your first value, the autoincrementfield will still work as expected:

只需NULL用作您的第一个值,该autoincrement字段仍将按预期工作:

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

回答by gahooa

Insert NULLinto the auto-increment field.

插入NULL自动增量字段。

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

我建议除非这是一个 hack 脚本,否则您使用字段名称。基本原理是,如果您向表中添加字段或更改其顺序,您的代码就会中断

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

相反,明确地使用字段名称,将来会更好。

回答by bharanikumar Bs

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

当我们在插入查询中尝试不使用列名时,我们应该省略任何列值,

Advise if above information is wrong.

以上信息有误请指教。

回答by Chaya Cooper

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.')';