Solved

PHP Array Help

Posted on 2012-03-31
8
166 Views
Last Modified: 2012-04-01
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
Comment
Question by:t3chguy
  • 4
  • 3
8 Comments
 
LVL 10

Expert Comment

by:acbxyz
ID: 37790746
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
 
LVL 1

Author Comment

by:t3chguy
ID: 37790984
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
 
LVL 10

Expert Comment

by:acbxyz
ID: 37791030
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
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 1

Author Comment

by:t3chguy
ID: 37791049
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
 
LVL 10

Accepted Solution

by:
acbxyz earned 500 total points
ID: 37791133
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
 
LVL 1

Author Comment

by:t3chguy
ID: 37792079
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
 
LVL 10

Expert Comment

by:acbxyz
ID: 37792561
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
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 37793037
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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
preventing spam with mailto 22 36
google map tracking website 5 24
Dynamic varibles 5 34
how to call a remote wordpress to use his  content in a loop 3 13
Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question