将表单中的数组值插入mysql

时间:2014-05-07 19:05:55

标签: php mysql arrays

我有3个PHP文件,在select.php文件中你必须选择你想要的表格数量。表格包含3个输入字段。 如下:

  <form method="post" action="index.php" >
     Continue insertion with <select name="counters" id="insert_rows">
    <option value="1">1</option>
    <option value="2" selected="selected">2</option>
    <option value="3">3</option>
    </select>
     rows
    <input type="submit" value="Go" />
    </form>

选择插入次数后,它会将数字传递给index.php,其中包含:

<?php
    echo "<form method = 'POST' action = 'process.php'>";
    for($counter = 0; $counter < $_POST['counters']; $counter++)
    {
        echo "Service Name: <input type = 'text' name = 'name[]' class = 'class_name'/><br/>";
        echo "Service Version :    <input type = 'text' name = 'version[]' class = 'class_name'/><br/>";
        echo "Service type :    <input type = 'text' name = 'type[]' class = 'class_name'/><br/>";
    }
    echo "<input type = 'submit' value = 'SEND'/>";
    echo "</form>";
?>

第三个文件process.php包含

<?php

    $name = array();
    $version = array();
    $type= array();

    $name = $_POST['name'];
    $version = $_POST['version'];
    $type= $_POST['type'];

    for($counter = 0; $counter < sizeof($name); $counter++)
    {
        echo "service_name #".($counter + 1).": ".$name[$counter]."<br />";
        echo "service_version #".($counter + 1).": ".$version[$counter]."<br />";
        echo "service_type #".($counter + 1).": ".$type[$counter]."<br />";
    }
    ?>

并且在我将值传递给它之后,它正确显示数据,如下所示

service_name#1:noway service_version#1:v1 service_type#1:私有 service_name#2:bandar service_version#2:v2 service_type#2:公开

所以我的问题是:如何在'process.php'文件中创建一个函数,将所有这些值插入到数据库中。

我创建了一个名为'services'的表,其中包含这些列“name,version,type”

我会等你的支持。 谢谢

1 个答案:

答案 0 :(得分:0)

我建议将第一个提交的计数值保存在第二个表单的隐藏输入中,然后您就可以遍历它并插入数据

<?php
  echo "<form method = 'POST' action = 'process.php'>";
  for($counter = 0; $counter < $_POST['counters']; $counter++)
  {
     echo "Service Name: <input type = 'text' name = 'name[]' class = 'class_name'/><br/>";
     echo "Service Version :    <input type = 'text' name = 'version[]' class = 'class_name'/><br/>";
     echo "Service type :    <input type = 'text' name = 'type[]' class = 'class_name'/><br/>";
  }
  echo '<input type="hidden" name="cntr" value="'.$_POST['counters'].'" />'
  echo "<input type = 'submit' value = 'SEND'/>";
  echo "</form>";
?>

现在,在您的process.php中,您将拥有:

if (!empty($_POST['cntr'])) {
   $query = 'INSERT INTO services (name, version, type) VALUES ';
   for ($x = 0; $x < $_POST['cntr']; $x++)
   {
      $query .= "('".mysqli_escape_string($_POST['name'][$x])."','"
                    .mysqli_escape_string($_POST['version'][$x])."','"
                    .mysqli_escape_string($_POST['type'][$x]).
                "'),";
   }
   $query = substr_replace($query, '', -1);

   mysqli->query($query);
}

无论我准备的只是一个示例,您都可以根据您的更改修改它