Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
287 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...