Import array to database

Hi, I have on array like below:

Array
(
    [1] => Array
        (
            [A] => green
            [B] => 12
        )

    [2] => Array
        (
            [A] => blue
            [B] => 13
        )

    [3] => Array
        (
            [A] => yellow
            [B] => 14
        )

    [4] => Array
        (
            [A] => red
            [B] => 15
        )

    [5] => Array
        (
            [A] => pink
            [B] => 16
        )

    [6] => Array
        (
            [A] => orange
            [B] => 17
        )

)

I want import array values to database in below format:
For example FOR array[1]:

[LIST]
[]Insert into xlsx (A) values (‘green’) where id=”1”
[
]Insert into xlsx (B) values (‘12’) where id=”1
[/LIST]”
And also for array[2]:

  • Insert into xlsx (A) values (‘blue) where id=”2”
  • Insert into xlsx (B) values (‘13’) where id=”2”

And etc…

How I can read array elements with foreach or for statements to achieve this?

Are you using the mysql or mysqli extension? What is the table structure of the table that the values will go into (and into which fields are they going)?

I use MySQL.
In this example fields names are: id , A, B with below value:
id: 1,2,3,4,5,6
A: green, blue, yellow,red, pink, orange
B: 12,13,14,15,16,17
and All fields type are varcher…


// a test array, just 2 items
$a = array(
1 => array( 'A' => 'green', 'B' => 12 ),
2 => array( 'A' => 'blue', 'B' => 13 ),
);

// create a loop of inserts - though you MUST know the fields names
// in advance - it is pos to do this without knowing them....
// added line br for readability

foreach( $a as $key=>$val){
echo "insert into xsls (A, B) values 
          ('" . $val['A'] ."','" . $val['B'] . "') where id = $key;" ;
}

// This ouputs:
insert into xsls (A, B) values ('green','12') where id = 1;
insert into xsls (A, B) values ('blue','13') where id = 2;


Thanks Cups.
Is there any way that i grab A & B programmatic instead of using absolute A & B in below code?


foreach( $a as $key=>$val){
echo "insert into xsls (A, B) values 
          ('" . $val['A'] ."','" . $val['B'] . "') where id = $key;" ;
}
$a = array(
1 => array( 'A' => 'green', 'B' => 12 ),
2 => array( 'A' => 'blue', 'B' => 13 ),
);

foreach( $a as $k=>$v){
$keys = join(array_keys($v), ',');
$values = join($v, "','");
 echo "insert into xsls ($keys) values ('$values') where id = $k;" ;
}

// gives
//insert into xsls (A,B) values ('green','12') where id = 1;
//insert into xsls (A,B) values ('blue','13') where id = 2;

This incorrectly quotes integers ie ‘13’, but mysql will accept them any way. Easy enough to detect if a a $value is an integer and quash the quote if neccessary.

Thanks Cups.
Sure it’s incorrectly quotes integers values, but i used it maybe value be string.

Will field B always only have numeric values? If so then it should be an INT field type.