php 使用 foreach 循环插入多个字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18156505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:04:10  来源:igfitidea点击:

insert multiple fields using foreach loop

phpmysqlforeach

提问by Kim Andersson

I have a problem when I want to insert multiple fields into one table.

当我想在一个表中插入多个字段时遇到问题。

Here's my form:

这是我的表格:

<h1>Add user</h1>
 <form method="post" action="index.php">

 <table>
    <thead>
        <th>Name</th>
        <th>Age</th>
    </thead>

    <tr>
        <td><input name="name[]" type="text" /></td>
        <td><input name="age[]" type="text" /></td>
    </tr>

    <tr>
        <td><input name="name[]" type="text" /></td>
        <td><input name="age[]" type="text" /></td>
    </tr>

    <tr>
        <td><input name="name[]" type="text" /></td>
        <td><input name="age[]" type="text" /></td>
    </tr>
</table>

 <input type="submit" name="submit" value="Submit" />
 </form>

And here's the submit code:

这是提交代码:

if (isset($_POST['submit'])) {

    foreach ($_POST as $val) {
        $name = $val['name'];
        $age = $val['age'];

        mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
    } 
}

The query inserts into the database, but not the values that I've entered.

查询插入到数据库中,但不是我输入的值。

Can someone please help me?

有人可以帮帮我吗?

回答by Mike Brant

You are doing a foreach on $_POSTrather than on the name/age arrays. You should be doing foreach on name or age array like this:

您正在$_POST对名称/年龄数组而不是对名称/年龄数组进行 foreach 。您应该像这样对 name 或 age 数组执行 foreach :

if (
   !empty($_POST['name']) && !empty($_POST['age']) &&
   is_array($_POST['name']) && is_array($_POST['age']) &&
   count($_POST['name']) === count($_POST['age'])
) {
    $name_array = $_POST['name'];
    $age_array = $_POST['age'];
    for ($i = 0; $i < count($name_array); $i++) {

        $name = mysql_real_escape_string($name_array[$i]);
        $age = mysql_real_escape_string($age_array[$i]);

        mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
    } 
}

I would also note that you are currently susceptible to SQL injection so I added the step of escaping your strings for name/age.

我还要注意,您目前很容易受到 SQL 注入的影响,因此我添加了为名称/年龄转义字符串的步骤。

I would also highly suggest simply making a single bulk insert into the DB instead of an insert of each record individually (I will leave that up to you to implement). This approach is almost always preferable from a performance standpoint.

我还强烈建议简单地将单个批量插入到数据库中,而不是单独插入每条记录(我将把它留给你来实现)。从性能的角度来看,这种方法几乎总是更可取的。

Finally, you REALLY should not be using mysql_*functions as they are deprecated. Consider changing to mysqli or PDO.

最后,您真的不应该使用mysql_*函数,因为它们已被弃用。考虑更改为 mysqli 或 PDO。

回答by Rahul

if (isset($_POST['submit'])) {

$i = 0;
foreach ($_POST as $val) {
    $name = $_POST['name'][$i];
    $age = $_POST['age'][$i];

    mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
    $i++;
  } 
}

This will solve your problem !

这将解决您的问题!

回答by Danilo Corrente Luiz

foreach($_POST['firstname'] as $key=>$value) {
    $firstname = $_POST['firstname'][$key];
    $lastname = $_POST['tipo'][$key];
    echo "Parte: $lastname";
    echo "<br>"; 
    echo "Tipo: $firstname";
    echo "<br>";
}

回答by arc_shiva

A little bit easier code which works for me well.

稍微简单一点的代码对我来说效果很好。

if (isset($_POST['submit'])) {
     $i = 0;
     for ((array) $_POST as $val) {
       $sql = "INSERT INTO users (name, age) VALUES (
                   '{$_POST["name"][$i]}','{$_POST["age"][$i]}'
               );
       mysql_query($sql);
       echo (!mysql_affetced_rows()) ? "Query Wrong" : "Query Okay";
       $i++;
     } 
    }

回答by jitendra parmar

below is the fxample how to inset multi row at one time

下面是如何一次插入多行的示例

$query_string = "INSERT INTO YOURTBL_NAME(column_1,column_2)VALUES";
    $data ="";
    for($i=0;$i<count($YOUR FILE ARRAY);$i++)
    {
        $data .='("'.$paramater_1[$i].'","'.$paramater_2.'"),';
    }
     $qry = substr($query_string.$data, 0, -1); 
     $result = mysql_query($qry);

回答by Pankaj Upadhyay

$education_institute_array = $_POST['education_institute'];
        $education_qualification_array = $_POST['education_qualification'];
        $education_start_date_array = $_POST['education_start_date'];
        $education_end_date_array = $_POST['education_end_date'];
        $education_note_array = $_POST['education_note'];
        for ($i = 0; $i < count($education_institute_array); $i++) {
            $education_institute = mysql_real_escape_string($education_institute_array[$i]);
            $education_qualification = mysql_real_escape_string($education_qualification_array[$i]);
            $education_start_date = mysql_real_escape_string($education_start_date_array[$i]);
            $education_end_date = mysql_real_escape_string($education_end_date_array[$i]);
            $education_note = mysql_real_escape_string($education_note_array[$i]);
            $sql_education_insert = "INSERT INTO `education` (`user_id`, `education_institute`, `education_qualification`, `education_start_date`, `education_end_date`, `education_note`) VALUES ('$user_id', '$education_institute', '$education_qualification', '$education_start_date', '$education_end_date', '$education_note')";
            $sql_result_education = mysql_query($sql_education_insert);
        }