php - insert multiple fields using foreach loop -
i have problem when want insert multiple fields 1 table.
here's 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 submit code:
if (isset($_post['submit'])) { foreach ($_post $val) { $name = $val['name']; $age = $val['age']; mysql_query("insert users (name, age) values ('$name', '$age')"); } }
the query inserts database, not values i've entered.
can please me?
you doing foreach on $_post
rather on name/age arrays. should doing foreach on name or age array 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']; ($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 users (name, age) values ('$name', '$age')"); } }
i note susceptible sql injection added step of escaping strings name/age.
i highly suggest making single bulk insert db instead of insert of each record individually (i leave implement). approach preferable performance standpoint.
finally, should not using mysql_*
functions deprecated. consider changing mysqli or pdo.
Comments
Post a Comment