PHP Array Help

I'm building a program to allow teachers to create homework assignments for their students.

They choose a number of questions for that assignment based of of a drop down selection.  The form is reloaded and the correct number of question boxes appear.

The problem I'm having is on POST.

If I post the number of questions and then the actual question, it's stored in one variable, but I need to separate it into the correct number of variables so that it matches the number of questions posted.

The example I'm working with involves 3 questions.  The code for the question is below:

                        for($h = 1; $h <= $totalquestions; ++$h)
                              echo "
                                          <td>Question " . $h . ": </td>
                                          <td><input type='text' name='question[]' value='".$question."'></td>

When I post the data, I can view all three questions that were typed into the box, but I cannot seem to be able to divide them up into separate variables to insert them into the database.

I know I could explode them into three different variables, but the next assignment or another teacher may choose anywhere between 1 and 25 questions.

Here is my post code:

$totalquestions = $_POST['totalquestions'];

      for($h = 1; $h <= $totalquestions; ++$h)
            $question = htmlentities($_POST['question'][$h]);
            echo $question . '<br />';
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Your example should work, but you miss the first question because indices don't start with 1 but 0.
An alternative way, and easier to debug, would be not to use [].
echo "<td><input type='text' name='question_" . $h . "' value='".$question."'></td>\n";
...and later...
$question = htmlentities($_POST['question_' . $h]);

If you need the questions in one array in the destination field, you can assign to any in the for loop like:
$question[$h] = htmlentities($_POST['question_' . $h]);

Also very helpful:
echo '<pre>'; var_dump($_POST); echo '</pre>';
t3chguyAuthor Commented:
That still doesn't produce separate variables for each part of the posted question.  

      for($h = 0; $h <= $totalquestions; ++$h)
            $question = htmlentities($_POST['question_' . $h]);

            echo $question . '<br />';

 $ins = "INSERT INTO homework `date`, `question`, `possibleanswers`, `spot1`, `spot2`,       `spot3`
VALUES('".$date."', '".$totalquestions."', '".$totalinputs."', '".$question."')";

echo $ins . '<br />';

The INSERT Query needs to have a separate variable for each posted variable so it can be added to a unique field.

If the query is in the for loop, I get three queries, If it's outside the query, I get one query, but only the last variable is posted.
That's the mistake. You overwrite $question with every loop-cycle and insert afterwards. You have to put the $ins and the command executing $ins inside the for loop. The closing curly brace has to be a few lines later.
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

t3chguyAuthor Commented:
But when its inside the loop it runs three queries, which makes three rows.

I need this all to be one record as it is one assignment.
Can you be more exact on how the database record should look like?

In a normalized database three questions means three records. If there are other information in the record, you should create a new table like "homeworkquestions".

If you really, really want one row with all questions, you can build the sql query over the whole for loop.
$sql = 'INSERT INTO homework (date';
$sql_fields = 'CURRENT_TIMESTAMP';
for ($h = 0; $h <= $totalquestions; ++$h) {
    $sql .= ', question_' . $h;
    $sql_fields .= ', "' . htmlentities($_POST['question_' . $h]) . '"';
$sql .= ') VALUES (' . $sql_fields . ');
// mysql_query($dbh, $sql);

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
t3chguyAuthor Commented:
Basically what you have there is exactly what I needed.  

The database will have one row per days worth of assignments, which is why I needed the number of questions to each be it's own field.  What you provided for me as the solution is exactly what I needed.

I know the way I did this probably the best way so if you had any other suggestions as to how I can layout the data, I'd be more than happy to hear them.

Thanks for your help
I know the way I did this probably the best way so if you had any other suggestions as to how I can layout the data, I'd be more than happy to hear them.

I know this doesn't make it easier at the beginning, but depending on what you want to do later, it makes it much easier then.
database layoutThe separate answers table right is if you want to provide multiple choice questions. If not you can omit it.

In this case you need two sql queries, one before the for loop and one inside. The best case to do this is using prepared statements. Then you don't have to worry about htmlentities() and breaking sql queries. With a mysql backend using PDO is the best way as far as I know.

Hope it helps.
Ray PaseurCommented:
If you want to post the HTML form that creates the questions, it would be helpful, and we can probably show you how to process the data with a tested and working example.

In the action script that processes the posted information, you will find it very useful to have these three lines of code near the top
echo "<pre>";
echo "</pre>" . PHP_EOL;

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.