dqby43944 2011-01-26 20:21
浏览 28
已采纳

PHP将多行POST到MySQL中

I have a table named fruits:

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

I would like to be able to add several rows at once using PHP.

I tried having two sets of two textboxes (for id and fruit) but that only insert 1 row, using the last set of textboxes.

EDIT:

Then what do I do if I have a table like this:

id      fruit       taste
1       Apple       Good
1       Banana      Okay
2       Apple       Good
2       Apple       Bad
2       Pear        Good
  • 写回答

5条回答 默认 最新

  • doulan1073 2011-01-26 20:27
    关注

    You need to name your text boxes properly using brackets [] to form an array, then loop through your POST'ed array to insert the data. Be certain you're escaping data before running your query by using mysql_real_escape_string or prepared queries.

    EDIT: Updating examples because OP appended information to the question.

    In the extended example you've provided, it looks like the taste only has a few choices. In that case, I would use a <select> element over a text box. Check out my examples for how, personally, I would do it.

    Form
    Notable changes: Using a simple loop in PHP, you can specify the number of fields you want to show and easily add other options to the taste select box. I'm placing an arbitrary number within the [] to be certain we link the fruit to the taste when we process the form.

    <?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" />';
    ?>
    

    Process Code
    Notable changes: I'm checking to make sure the fruit has a value, otherwise it won't insert. I'm using that arbitrary value (which is the array key $k) to select the taste that matches the fruit.

    <?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);
        }
      }
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测