Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 202
  • Last Modified:

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 "
                                    <tr>
                                          <td>Question " . $h . ": </td>
                                          <td><input type='text' name='question[]' value='".$question."'></td>
                                    </tr>
                                    ";
                              }


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 />';
            }
0
t3chguy
Asked:
t3chguy
  • 4
  • 3
1 Solution
 
acbxyzCommented:
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>';
0
 
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.
0
 
acbxyzCommented:
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.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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.
0
 
acbxyzCommented:
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

0
 
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
0
 
acbxyzCommented:
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.
0
 
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>";
var_dump($_POST);
echo "</pre>" . PHP_EOL;

Open in new window

0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now