insert multiple fields using foreach loop

前端 未结 6 726
逝去的感伤
逝去的感伤 2020-12-08 17:54

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

Here\'s my form:

Add user

6条回答
  •  渐次进展
    2020-12-08 18:40

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

    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.

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

提交回复
热议问题