如何在MySQL中插入表单数组值? [英] How to insert form array values into MySQL?

查看:68
本文介绍了如何在MySQL中插入表单数组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困住了,我想将如下所示的数组字段中的表单数据插入MySQL:

I'm stuck, I want to insert form data from array fields like below into MySQL:

<input type='text' name='name[]' />` and `<input type='text' name='url[]' />

我知道像这样的示例如何输出一个字段的数据

I know how to output the data for one field like this example

foreach($_POST['name'] as $name)
{
  echo $name;
}

但是在我的表单中,我同时拥有<input type='text' name='name[]' /><input type='text' name='url[]' />,如何才能使其正常工作?

But in my form I have both <input type='text' name='name[]' /> and <input type='text' name='url[]' /> how can I get this to work correctly?

推荐答案

我会尽量避免一遍又一遍地查询数据库,而只是将所有内容放在一个大的insert语句中:

I would try and avoid querying the DB over and over and just put everything in one big insert statement:

$query = "INSERT INTO table1 (name, url) VALUES ";
foreach($_POST['name'] as $i => $name) 
{ 
  // Get values from post.
  $name = mysql_real_escape_string($name);
  $url = mysql_real_escape_string($_POST['url'][$i]);

  // Add to database
  $query = $query." ('$name','$url') ,";
}
$query = substr($query,0,-1); //remove last char
$result = mysql_query($query);

这样,您只需要打一次数据库,就可以更快地插入数据库.
另一个好处是,如果引擎支持事务(InnoDB等),则所有插入都发生在单个事务中.

That way you only have to hit the database once, making the insert much faster.
An other benefit is that if the engine supports transactions (InnoDB et al) all inserts happen in a single transaction.

这篇关于如何在MySQL中插入表单数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆