Jump to content

loop problem


gerkintrigg

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,
Link to comment
https://forums.phpfreaks.com/topic/18715-loop-problem/
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
Link to comment
https://forums.phpfreaks.com/topic/18715-loop-problem/#findComment-80679
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 :)
Link to comment
https://forums.phpfreaks.com/topic/18715-loop-problem/#findComment-80688
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,
Link to comment
https://forums.phpfreaks.com/topic/18715-loop-problem/#findComment-80692
Share on other sites

Archived

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

×
×
  • 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.