开发者

How can I grab and store multiple $_POST Variables in a for each loop?

So currently I am using a 3rd party software application to get results from various surveys. This application is sending the results to a page via a $_POST variable.

So for example..

$demoEMP = $_POST['demoEMP'];

This just stores the answer from the specific question into a variable.

What I want to do is store Questions 1-20 in POST variables and Insert them into a database.. What I don't want to do is write 20+ Insert commands or 20+ $var = $_POST['var']

So I was thinking a for loop would do the trick... This is what I have so far... based on looking at various methods and tutorials. =/

for ($i = 0; $i < 55; $i++) {
$answer = "Q{$i}";
echo $_POST[$answer];
}

Am I even on the right track? Thanks for your help!

UPDATE:: Kas' solution worked great.

I used something like this...

foreach ($_POST as $i => $v)
{
if (preg_match("/^Q\d+$/",$i)) {

// Here we insert value $v to database
$query_2 = mysql_query("INSERT INTO SGresult VALUES ('', '', '$pID', '$SGQID','$v')") or die('Error: '.mysql_error ());

} }

However, I开发者_运维知识库 am now trying to figure a way to add an ID to the question and have that ID auto increment... on every insert. I thought I could do something like $SGQID++ but that does not seem to be working.. anyone have any thoughts?

Thanks again!

okay after some more tinkering it seems the placement of the ++ was off and it needed to be after the query... the correct code is as follows.

$SGQID= 1;

foreach ($_POST as $i => $v)
{

if (preg_match("/^Q\d+$/",$i)) {

// Here we insert value $v to database
$query_2 = mysql_query("INSERT INTO SGresult VALUES ('', '', '$pID', '$SGQID','$v')") or die('Error: '.mysql_error ());
$SGQID++; //added value to increment Question ID in DB

}
}


foreach ($_POST as $i => $v) {
  if (preg_match("/^Q\d+$/",$i)) {
    // Here we insert value $v to database
  }
}


You can loop over the $_POST array itself:

foreach ($_POST as $key => $value) {
    // Filter on value of $key
    // In this case only keep variables that start with a Q
    if (! substr($key, 0, 1) == 'Q') {
        continue;
    }

    // Do something with value
    echo $_POST[$key];     
}

If you want to assign the values to PHP variables with the same name as the key of the $_POST array you can use variable variables:

$$key = $value

The value of $_POST['demoEMP'] will then be assigned to $demoEMP.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜