Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

PHP Array Help

Posted on 2012-03-31
8
Medium Priority
?
198 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 2000 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 111

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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

722 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