Solved

PHP Array Help

Posted on 2012-03-31
8
171 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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
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 …

820 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