PHP将多行POST到MySQL中

时间:2011-01-26 20:21:03

标签: php mysql rows

我有一个名为fruits的表:

id      fruit
1       Apple
1       Banana
2       Apple
2       Apple
2       Pear

我希望能够使用PHP一次添加几行。

我尝试了两组两个文本框(用于id和fruit),但只使用最后一组文本框插入1行。

编辑:

如果我有这样的表,我该怎么办:

id      fruit       taste
1       Apple       Good
1       Banana      Okay
2       Apple       Good
2       Apple       Bad
2       Pear        Good

5 个答案:

答案 0 :(得分:3)

您需要使用方括号[]正确命名文本框以形成数组,然后遍历POST'ed数组以插入数据。在使用mysql_real_escape_string或准备好的查询运行查询之前,请确保您正在转义数据。

编辑:更新示例,因为OP会在问题中附加信息。

在您提供的扩展示例中,看起来taste只有几个选择。在这种情况下,我会在文本框中使用<select>元素。看看我的例子,我个人会这样做。

<强>表格
值得注意的变化:在PHP中使用简单循环,您可以指定要显示的字段数,并轻松地将其他选项添加到品味选择框中。我在[]中放置一个任意数字,以确保我们在处理表单时将水果与味道联系起来。

<?php
$n = 5; //Number of fields to show
$tastes = array('Great', 'Good', 'Okay', 'Bad', 'Horrible');

for($i=0;$i<$n;$i++) {
  echo '<p>';
  echo '<input type="text" name="fruit['.$i.']" /> ';
  echo '<select name="taste['.$i.']">';
  foreach($tastes as $t) {
    echo '<option value="'.htmlentities($t).'">'.$t.'</option>';
  }
  echo '</select>';
  echo '</p>';
}
echo '<input type="submit" name="submit" value="Submit" />';
?>

流程代码
值得注意的变化:我正在检查水果是否有值,否则不会插入。我正在使用该任意值(这是数组键$k)来选择与水果相匹配的味道。

<?php
if($_POST['submit']) {
  foreach($_POST['fruit'] as $k => $v) {
    if(!empty($v)) {
      $query = "INSERT INTO fruits (fruit, taste) VALUE ('".mysql_real_escape_string($v)."', '".mysql_real_escape_string($_POST['taste'][$k])."')";
      mysql_query($query);
    }
  }
}
?>

答案 1 :(得分:1)

使用内爆函数进行单次插入。

您的HTML

<input type="text" name="fruit[]" />
<input type="text" name="fruit[]" />
<input type="text" name="fruit[]" />

你的PHP

foreach($_POST['fruit'] as $fruit) $values[] = "('".mysql_real_escape_string($fruit)."')";
if(count($values) > 0) mysql_query("INSERT INTO fruits (fruitName) VALUES " . implode(',', $values));

答案 2 :(得分:0)

在insert语句中只需添加值,如下所示:

INSERT INTO tbl_name(a,b,c)VALUES(1,2,3),(4,5,6),(7,8,9);

所以对你的例子来说,

INSERT INTO fruit(fruit)VALUES('Orange'),('Lemon'),('Lime');

应该有效。

http://dev.mysql.com/doc/refman/5.5/en/insert.html

答案 3 :(得分:0)

MySQL在单个查询中支持多个插入:

INSERT INTO table (field1, field2) VALUES (values1a, values2a), (values1b, values2b), etc...

答案 4 :(得分:0)

您可以制作一个html数组元素,例如

in html

<form action='save.php' method='post'/>
<input name='fruits[]' value='' />
<input name='fruits[]' value='' />
<input name='fruits[]' value='' />
</form>

然后在save.php中

$fruits = '';
foreach($_POST['fruits'] as $fruit) {
 $fruits .= "({$fruit}),"
}

 $fruits = rtrim($fruits,',');

$sql = "INSERT INTO fruits(fruit) VALUES {$fruits}";