Jump to content

MySQL INSERT multiple record from FORM


mtran

Recommended Posts

I have simple form with mutiples of 2 fields: status1 / name1,status2 / name2...

[code]
<form method="post" action="test1_edit.php">
<input type='checkbox' name='status[]' value='active'>Status1
<input name='name[]' type="text" />Name1<br />

<input type='checkbox' name='status[]' value='active'>Status2
<input name='name[]' type="text" />Name2<br />

<input name="submit" type="submit" /><br />
</form>
[/code]

The test1_edit.php file is as below. If I only [!--coloro:#FF0000--][span style=\"color:#FF0000\"][!--/coloro--]INSERT $status, the form is working fine, but I don't how to INSERT both $status and $name in FOREACH[!--colorc--][/span][!--/colorc--].

[code]
$status=$_POST['status'];
$name=$_POST['name'];

foreach ($status as $status )
{ mysql_query ("INSERT INTO test (status)
VALUES('$status')",$connection);  // This works fine

//mysql_query ("INSERT INTO test (status, name))
VALUES('$status','$name')",$connection);// This doesn't work.

if (mysql_affected_rows()==1){
  continue;
  } else {
    echo "Something went wrong!";
    break;
}
}
header("Location: test1.php"); ?>
[/code]

Thanks for help!
Link to comment
Share on other sites

I'll assume both $_POST['status'] and $_POST['name'] are arrays with the same length. Then:

[code]for ($i=0; $i<count($_POST['status']); $i++) {
   $status = $_POST['status'][$i];
   $name = $_POST['name'][$i];
   mysql_query ("INSERT INTO test (status, name))
VALUES('$status','$name')");
}[/code]

Use this instead of the foreach loop.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.