简体   繁体   English

在单个查询中将多个输入存储在数据库中

[英]Storing multiple inputs in database in single query

<form method="post" action="formProcessing.php">
  <input type="text" name="uses[]">
  <input type="text" name="uses[]">
  <input type="text" name="uses[]">
</form>

I have two database tables one called info other uses.我有两个数据库表,一个称为信息其他用途。 info table contain column name inf_num , Is there a way where i can get the last row inf_num and insert the above inputs in uses in one query.信息表包含列名inf_num ,有没有办法我可以获得最后一行 inf_num 并在一个查询中插入上述输入。 For instance if i was to do it manually i would check the last row myself so if it's 10 i would do the below:例如,如果我要手动执行此操作,我会自己检查最后一行,因此如果是10,我将执行以下操作:

INSERT INTO uses (id, uses) VALUES (10, 'useZero'), (10, 'useOne'), (10, 'useTwo');


How would i go about doing it dynamically with php using the above form:我将如何使用上述表单使用 php 动态执行此操作:

you can create trigger on uses table to set last inserted id of info table.您可以在使用表上创建触发器来设置信息表的最后插入的 id。

CREATE TRIGGER uses_before_insert_trigger BEFORE INSERT ON `uses` FOR EACH ROW
      BEGIN                            
           SET NEW.id = (select id from info order by id desc LIMIT 1);    
      END

After, create trigger you can execute insert query directly.之后,创建触发器就可以直接执行插入查询了。

INSERT INTO uses (uses) VALUES ('10'),('20'),('26');

INSERT INTO user( id, uses ) SELECT MAX(id), 'userOne' FROM info UNION ALL SELECT MAX(id), 'userTwo' FROM info;

Try To Make A Query Like This尝试进行这样的查询

<?php

//Your input is array of your input.
$yourInput = array(10,20,26);

$query = "INSERT INTO uses (id, uses) VALUES ";

foreach($yourInput as $value ){
 $query .= "(10, '$value')".",";
}

echo $query;
//Output
INSERT INTO uses (id, uses) VALUES (10, '10'),(10, '20'),(10, '26')

Tested Here Than Execute this Query在这里测试然后执行这个查询

But Remember Youe code is not secure.但请记住 Youe 代码并不安全。 it is possible to do a sql injection so kindly read this note.可以进行 sql 注入,因此请阅读此说明。 and make it more secure.并使其更安全。

We can make it possible via query as well.我们也可以通过查询来实现。

INSERT INTO uses( id, uses ) VALUES ((SELECT MAX(inf_num) from info), 
'useOne', (SELECT MAX(inf_num) from info), 'useTwo', (SELECT MAX(inf_num) from 
info), 'useThree')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM