trh88
trh88

Reputation: 633

Multidimensional array to MySQL

I've got a form like so:

    Question: <input type="text" name="question[][text]" id="question" />
    Type: 
    <select name="question[][type]" id="type">
    <option value="1to5scale">1 to 5 scale</option>
    <option value="freetext">Open text</option>
    </select>

This gets repeated depending on how many items the user wants (cloned through jquery). And my php to action the form contains:

foreach ( $_POST['question'] as $key=>$question )
{
    if ($key >= 1) {
    $question_text = $question['text'];
    $type = $question['type'];
    $query = " INSERT INTO questions (question_text, survey_id, type) ". 
    " VALUES ('$question_text','$survey_id', '$type')"; 
    mysql_query($query) or die('Error ,query failed');
    }
}

Each question has a text item and a type item. However in the DB it's adding one row per question item (if that makes sense...), rather than one row per complete question. Any ideas where I'm going wrong, it's quite hard to debug forms I'm finding...

Upvotes: 0

Views: 107

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191799

Change the form element name from question[][type] to question[type][]. What this form does is add to the question array for each form element ([] means add a new array element).

As the comment implies, make sure you sanitize the input.

Upvotes: 1

Related Questions