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!

Link to comment
Share on other sites

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)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.