Jump to content

How to Insert an Array Into a MYSQL Table?


phido

Recommended Posts

Hello All,

 

Working on a php / mysql project to do exactly what is described here … http://mechiwiki.com/tech/code/inserting-array-values-into-mysql-table/

 

Using  print_r  my array displays as follows:

 

Array ( [0] => Array ( [apples] => 70 [oranges] => 30 [pears] => 90 ) [1] => Array ( [apples] => 30 [oranges] => 20 [pears] => 10 ) [2] => Array ( [apples] => 60 [oranges] => 50 [pears] => 10 )  ... )

 

The problem I’m having arises in the while statement where I’m trying to ready the values for insertion into the mysql query. Instead of producing a properly formatted set of values for use in the query, the while statement produces this …

 

70, 30, 90, '', '', ''30, 20, 10, '', '', ''60, 50, 10, '', '', ''

 

Any thoughts on how to fix this, or other ways to approach this, are welcome. Thanks!

Assuming the values are inserted into a properly normalized database table, each set in its own record, and each value in its own field . . .

 

<?php
$your_array = Array (
0 => Array ( 'apples' => 70, 'oranges' => 30, 'pears' => 90 ),
1 => Array ( 'apples' => 30, 'oranges' => 20, 'pears' => 10 ),
2 => Array ( 'apples' => 60, 'oranges' => 50, 'pears' => 10 )
);

foreach( $your_array as $value ) {
$str[] = "(" . implode(", ", $value) . ")";
}
$query = "INSERT INTO `table` (`field_1`, `field_2`, `field_3`) VALUES " . implode( ", ", $str);
echo $query; // replace the echo with your query execution after testing . . . 
?>

 

Returns:

INSERT INTO `table` (`field_1`, `field_2`, `field_3`) VALUES (70, 30, 90), (30, 20, 10), (60, 50, 10)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.