SQL - 将多个行值插入到单个列中
我需要有关将值插入到不同行的单列中的方法的帮助。
现在,我有一个内爆数组,它给我一个如下所示的值:
('12', '13', '14')
这些数字是我希望插入数据库的新 ID。
我用来爆破数组的代码是这样的:
$combi = "('".implode("', '",$box)."')"; // 其中 $box 是初始数组
我计划使用的查询卡在这里:
mysql_query("INSERT INTO
studentcoursedetails
(studentID
) VALUES
一种选择是重复此操作,但我不能,因为数组会循环;可能有 3 个 ID,也可能有 20 个。
循环似乎不对。任何帮助将不胜感激。
I need help on a method of inserting values into a single column on different rows.
Right now, I have an imploded array that gives me a value such as this:
('12', '13', '14')
Those numbers are the new IDs of which I wish to insert into the DB.
The code I used to implode the array is this:
$combi = "('".implode("', '",$box)."')"; // Where $box is the initial array
The query of which I plan to use gets stuck here:
mysql_query("INSERT INTO
studentcoursedetails
(studentID
) VALUES
One option would be to repeat this, but I cant, because the array will loop; there might be 3 IDs, there might be 20.
A loop doesn't seem right. Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要在表中插入多个值,您应该使用 (value1), (value2) 语法:
PS:此功能称为行值构造函数,自 SQL-92 起可用
For inserting more than one value into a table you should use (value1), (value2) syntax:
PS: This feature is called row value constructors and is available since SQL-92
你能不能做这样的事情:
这将直接在你的数组上工作,为 $box 中的每个值插入一个新行,并且还可以防止需要将数组内爆为逗号分隔的字符串
将 ids 存储为逗号分隔的字符串最初看起来可能是这样就像一个简单的模型,但从长远来看,这会给您在尝试使用非标准化数据库时带来无穷无尽的麻烦。
Can you not do something like this:
This will work directly on your array, insert a new row for each value in $box and also prevent the need to implode the array to a comma delimited string
Storing ids as a comma delimited string might initially seem like a simple model but in the long term this will cause you no end of trouble when trying to work with a non-normalised database.
某些类型的 sql 允许复合插入:
Some flavors of sql allow compound inserts:
如果您使用 MySQL,则可以在一个句子中插入多个值:
因此,您只需在 PHP 中构建该字符串即可。
If you are using MySQL, you can insert multiple values in a single sentence:
So, you just need to build that string in PHP and you are done.
您仍然可以通过 implode 创建语句。只是不要使用 VALUES;使用 SELECT 代替
SELECT .. union
可跨许多 dbms 移植。请注意 ID - 如果它们是数字,请勿引用它们。
You can still create the statement via implode. Just don't use VALUES; use SELECT instead
The
SELECT .. union
is portable across many dbms.Note on the IDs - if they are numbers, don't quote them.
检查是否存在可对数组参数进行操作的 mysql_query 函数的变体。
Check to see if there is a variant of the mysql_query function that will operate on an array parameter.