Jump to content

Archived

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

phileplanet

Inserting Array Values into table columns.

Recommended Posts

I basically want each value in the array to go into its own column. here's what I have so far:

[code]$columns = array();
$values = array();
foreach($formfields as $field) {
    $column = $field[2];
    $value = $_POST["$column"];
    array_push($columns, $column);
    array_push($values, $value);
}
$q = mysql_query("INSERT INTO $table($columns) VALUES($values)") or die (mysql_error());?>[/code]
When I try to INSERT, it gives me "Unknown column 'Array' in 'field list'". Any solutions?

Share this post


Link to post
Share on other sites

You have to convert the array into a string and put commas in between:


$q = mysql_query("INSERT INTO $table (" . implode(', ', $columns) . ") VALUES(" . implode(', ', $values) . ")") or die (mysql_error());

Share this post


Link to post
Share on other sites
I prefer this way but i'm not sure if it's correct.
[code]
$i1 = implode(', ', $columns);
$i2 = implode(', ', $values);
$q = mysql_query("INSERT INTO $table($i1) VALUES($i2)") or die (mysql_error());[/code]

Share this post


Link to post
Share on other sites
I was going to show it that way. It's up to you what you want to do. It's best to put a space after the table name.

Instead of asking if it's right, I invite everyone just to always try it before posting. That's one way we all learn.


Good luck.

Share this post


Link to post
Share on other sites
Yes, good. Well done. I recommend that you use one of these on each value before being inserted/updated in the table:

mysql_real_escape_string(), mysql_real_escape_string(), or addslashes()

[a href=\"http://us2.php.net/manual/en/function.mysql-escape-string.php\" target=\"_blank\"]http://us2.php.net/manual/en/function.mysq...cape-string.php[/a]

[a href=\"http://us2.php.net/manual/en/function.addslashes.php\" target=\"_blank\"]http://us2.php.net/manual/en/function.addslashes.php[/a]

But first make sure you know what you're magic_quotes setting is before applying the above type of functions on form data. See:

[a href=\"http://us2.php.net/manual/en/function.get-magic-quotes-gpc.php\" target=\"_blank\"]http://us2.php.net/manual/en/function.get-...-quotes-gpc.php[/a]

Share this post


Link to post
Share on other sites

×

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.