Jump to content


Photo

MySQL INSERT multiple record from FORM


  • Please log in to reply
2 replies to this topic

#1 mtran

mtran
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 05 June 2006 - 11:31 PM

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

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

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

$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"); ?>

Thanks for help!

#2 poirot

poirot
  • Members
  • PipPipPip
  • Advanced Member
  • 646 posts
  • LocationAustin, TX

Posted 06 June 2006 - 02:30 AM

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

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

Use this instead of the foreach loop.
~ D Kuang

#3 mtran

mtran
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 06 June 2006 - 02:58 AM

This works fine. Thanks for your prompt help, Poirot. Really appreciated!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users