使用 foreach 循环插入多个字段

2021-12-26 00:00:00 foreach php mysql

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

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

这是我的表格:

<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>

这是提交代码:

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.

有人可以帮我吗?

推荐答案

您正在对 $_POST 而不是 name/age 数组执行 foreach.您应该像这样对 name 或 age 数组执行 foreach:

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

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')");
    } 
}

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

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

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

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.

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

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

相关文章