Jump to content

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


cK

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/544-advanced-foreach_post-as-key-item/
Share on other sites

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.

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.