Jump to content


Photo

Inserting Array Values into table columns.


  • Please log in to reply
5 replies to this topic

#1 phileplanet

phileplanet
  • Members
  • PipPip
  • Member
  • 19 posts

Posted 26 March 2006 - 12:25 AM

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

$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());?>
When I try to INSERT, it gives me "Unknown column 'Array' in 'field list'". Any solutions?


#2 toplay

toplay
  • Staff Alumni
  • Advanced Member
  • 973 posts

Posted 26 March 2006 - 01:29 AM


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());

#3 phileplanet

phileplanet
  • Members
  • PipPip
  • Member
  • 19 posts

Posted 26 March 2006 - 01:43 AM

I prefer this way but i'm not sure if it's correct.
$i1 = implode(', ', $columns);
$i2 = implode(', ', $values);
$q = mysql_query("INSERT INTO $table($i1) VALUES($i2)") or die (mysql_error());


#4 toplay

toplay
  • Staff Alumni
  • Advanced Member
  • 973 posts

Posted 26 March 2006 - 01:53 AM

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.


#5 phileplanet

phileplanet
  • Members
  • PipPip
  • Member
  • 19 posts

Posted 26 March 2006 - 01:59 AM

Okay I got it. the problem was that the VALUES had to be quoted and they weren't. Thanks for your help!

#6 toplay

toplay
  • Staff Alumni
  • Advanced Member
  • 973 posts

Posted 26 March 2006 - 04:34 AM

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]




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users