Jump to content


Photo

advanced foreach($_POST as $key => $item)


  • Please log in to reply
2 replies to this topic

#1 cK

cK
  • Members
  • PipPip
  • Member
  • 11 posts

Posted 04 June 2003 - 06:53 PM

Hi,

Currently I have the following fields in my online form,


<input type="text" name="var1">

<input type="text" name="var2">

<input type="text" name="var2">


and save everything to the database like:


$query = "INSERT INTO test_jobapplications (var1,var2,var3) VALUES (\'" . $_POST[\'var1\'] . "\',\'". $_POST[\'var2\'] . "\',\'" $_POST[\'var3\'] . "\')";

mysql_query($query) or error ("Unable to connect to SQL server. Try again later.");


But now I\'m working on a time-sheet system I would like to be able to have the following type of input-boxes and have a routine to extract each set a vars into an array so I could loop true the array and save each set of vars in the database.


<input type="text" name="1-var1">

<input type="text" name="1-var2">

<input type="text" name="1-var3">



<input type="text" name="2-var1">

<input type="text" name="2-var2">

<input type="text" name="2-var3">



<input type="text" name="3-var1">

<input type="text" name="3-var2">

<input type="text" name="3-var3">


So I made the following snippet:


while (list ($key, $val) = each ($_GET)) {



	if (eregi("-", $key)) {

	

  $tmp = explode("-", $key);

  

  $id   = $tmp[0];

  $name = $tmp[1];

  

  $data[$id][$name] = $val;



	}

}


I\'m only wondering: is this the best/safest way? And how to loop true the array to save the data in the sql-database?! I have no clue!

Thanks in advance,

cK

#2 barbatruc

barbatruc
  • Members
  • PipPip
  • Member
  • 28 posts
  • LocationMontreal, Quebec, Canada

Posted 05 June 2003 - 01:48 PM

What you did may be safe, but you could do something like this:
<input type="text" name="var1[]">

<input type="text" name="var2[]">

<input type="text" name="var3[]">



<input type="text" name="var1[]">

<input type="text" name="var2[]">

<input type="text" name="var3[]">



<input type="text" name="var1[]">

<input type="text" name="var2[]">

<input type="text" name="var3[]">
And then after that:
foreach($_POST[\'var1\'] AS $id => $value) {

  $var1 = $_POST[\'var1\'][$id];

  $var2 = $_POST[\'var2\'][$id];

  $var3 = $_POST[\'var3\'][$id];

  // build your SQL with $var1, $var2, $var3!

}
Hope this helps!

JP.
Unfortunately, PHP \'empowered every moron with a copy of Windows notepad to be \"web programmers\". (...) Give PHP a real INFRASTRUCTURE. Use PEAR!!!\'

#3 cK

cK
  • Members
  • PipPip
  • Member
  • 11 posts

Posted 05 June 2003 - 03:33 PM

Hope this helps!


No, not al all....(because I didn\'t get your tric.)

Could you explain it? Don\'t forget I need all vars seperate and need to figure out how to go true the array and save eveything in the database.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users