Jump to content

Archived

This topic is now archived and is closed to further replies.

gerkintrigg

loop problem

Recommended Posts

Hi everyone!

I'm having a problem writing to the database from a loop. I have a dynamically created form, meaning that i don't know how many fields there will be in it and I'm trying to write each field to the database.

I'm using this code:[code]foreach($_POST as $varName => $value)
  {
  if (($value !="Submit") &&($varName!="Submit")){
  mysql_query("INSERT INTO `options` ( `option` , `id` )
VALUES ('".$value."', '".$r['option_id']."');");
  echo $varName.' | '.$value.'<br>';
      }
  }[/code] but it's only writing the first field in the list, not subsequent ones.

Can anyone suggest a resolution to it?
Thanks,

Share this post


Link to post
Share on other sites
[code]foreach($_POST as $varName => $value)
  {
  if (($value !="Submit") &&($varName!="Submit")){
  mysql_query("INSERT INTO `options` ( `option` , `id` )
VALUES ('".$value."', '".$r['option_id']."');");
  echo $varName.' | '.$value.'<br>';
      }
  }[/code]

needs to be

[code]foreach($_POST as $varName => $value)
  {
  if (($value !=="Submit") &&($varName!=="Submit")){
  mysql_query("INSERT INTO `options` ( `option` , `id` )
VALUES ('".$value."', '".$r['option_id']."');");
  echo $varName.' | '.$value.'<br>';
      }
  }[/code]

common mistake using = instead of ==

that *should sort it

Share this post


Link to post
Share on other sites
nope... I did it before using the single = (and in the != context it should be correct), I've changed the code to what you suggested, but it still only writes the first option. ?? weird.

Share this post


Link to post
Share on other sites
try

[code]foreach($_POST as $varName => $value) {
  if (($value !=="Submit") &&($varName!=="Submit")){
  mysql_query("INSERT INTO `options` ( `option` , `id` )
VALUES ('".$value."', '".$r['option_id']."')") or die(mysql_error());;
  echo $varName.' | '.$value.'<br>';
  }
}[/code]


just taken off the ; at end of query and also added or DIE which will give us the error generated from mysql if there is a problem..
another way is to not use the query at all and just run

[code]foreach($_POST as $varName => $value)
  {
echo $varName.' | '.$value.'<br>';
  }[/code]

see if it returns all :)

Share this post


Link to post
Share on other sites
the echo on it's own returns everything fine, which makes me think there's not a problem, but the SQL is still only uploading the first one...

Oops... I set the ID field as a primary key, which would mean that it couldn't allow more than one with the same ID, I feel so stupid!

Thanks for your help (it was the OR DIE command that could have saved me a lot more time...) ;o)
Cheers,

Share this post


Link to post
Share on other sites

×

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.