0

I have 2 dimensional array to be save into mysql. The problem is, how do i get the data from that array and save it into DB Here is my array:

Array
(
[1a] => Array
    (
        [ans] => 1
    )

[2a] => Array
    (
        [ans] => 1
        [oth] => ABC
    )

[3a] => Array
    (
        [ans] => 1
    )

[3b] => Array
    (
        [ans] => 2
    )

[3f] => Array
    (
        [oth] => 
    )

)

so when saved, it will be look like this:

| qid | ans | oth |
===================
|  1a |  1  |     |
|  2a |  1  | ABC |
|  3a |  1  |     |
|  3b |  2  |     |
|  3f |     |     |
===================

please help me n thanks.

1
  • Could you provide a bit more information regarding your columns, whether or not the columns accept NULL values, if not what are their defaults? It'll make a big difference in the structure of any solution. Commented Jan 18, 2012 at 4:54

2 Answers 2

1

Let say you have the array with name x

foreach($x as $key=>$details)
{
   $qid = $key;
   $ans = $details["ans"];
   $oth = $details["oth"];
   //Then Save to DB
   // Insert into table (qid,ans,oth) values('$qid',$ans,'$oth') ...

}
Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't cover the entries where those array keys don't exist. The OP will need to provide column details (NULL, DEFAULT) before you can handle them though.
I think the vars $oth and $ans will get the NULL value if there was no array key while looping , then the default value of the columns in the table will be inserted . thank you .
It wouldn't work that way sadly. If you don't use isset($array[<key] the script will though errors and if it did Sql wouldn't translate the ("1a",,) missing values into NULL.
I agree the second sentence ("1a",,) , but i think it won't throw php errors .
It'll depend on the version of Php; they've been strict about array keys since 5.3
0
foreach ($your_array as $qid => $value) {
   $ans = isset($value['ans']) ? $value['ans'] : null;
   $oth = isset($value['oth']) ? $value['oth'] : null;
   //then you get the $qid, $ans, $oth and insert them to the db.
   ....
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.