Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I grab and store multiple $_POST Variables in a for each loop?
    primarykey
    data
    text
    <p>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.</p> <p>So for example..</p> <pre><code>$demoEMP = $_POST['demoEMP']; </code></pre> <p>This just stores the answer from the specific question into a variable.</p> <p>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'] </p> <p>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. =/</p> <pre><code>for ($i = 0; $i &lt; 55; $i++) { $answer = "Q{$i}"; echo $_POST[$answer]; } </code></pre> <h2>Am I even on the right track? Thanks for your help!</h2> <p>UPDATE:: Kas' solution worked great.</p> <p>I used something like this...</p> <pre><code>foreach ($_POST as $i =&gt; $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 ()); </code></pre> <p>} }</p> <p>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?</p> <p>Thanks again!</p> <p>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.</p> <pre><code>$SGQID= 1; foreach ($_POST as $i =&gt; $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 } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload