简体   繁体   中英

Insert array to mysql database

I got an array inside a php programm that looks like this:

$db=Array ( [1] => 1 [2] => 2 [3] => 2 [4] => 2 [5] => 3 [6] => 4 [7] => 4 [8] => 5 );

It is an associative array, and I want to store it in my mysql database with this structure:

id  date    fd1     fd2     fd3     fd4     fd5     fd6     fd7     fd8

mysql_query("INSERT INTO table2 (date) VALUES(NOW(),'$db')");

id is set to AUTO_INCREASE and NOW() stores the date for every entry

But my main problem is how to assign array field [1] to fd1 column and post "value" in it

Any Help appreciated

$sql_fields = 'date';
$sql_values = 'NOW()';
for ($i=1; $i<=8; $i++) {
    $sql_fields .= ',fd'.$i;
    $sql_values .= ','.$db[$i];
}
$sql = 'INSERT INTO `table2` ('.$sql_fields.') VALUES ('.$sql_values.')';
mysql_query($sql);

EDIT:

there's no impact for speed here. you can also use implode instead

// create fdX list
$fields = array_map(function($v){return '`fd'.($v++).'`';}, range(1,8));
// the sql query
$sql = 'INSERT INTO `table2` 
    (`date`,'.implode(',',$fields).') VALUES (NOW(),'.implode(',',$db).')';

You can join array elements into a string using implode

$db = Array( [1] => 1 [2] => 2 [3] => 2 [4] => 2 [5] => 3 [6] => 4 [7] => 4 [8] => 5 );
$db = implode(' ', $db); // Join the array into a string with space as the separator
// Run your insert query
// mysql_query(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM