Question

As I've found several ways to create array and insert it into the mysql query, I made a code below which obviously doesn't work. I pay attention on brackets and commas, but I missed something around VALUES.

Because, that is the part that is not working, the first part of the query (columns) is written properly (I think) but I got stuck with the second implode.

Please help.

$f_ids = array(f1, f2, f3, f4, f5);
$f_list = implode(',', $f_ids);

$val_ids = array($val[1],$val[2],$val[3],$val[4],$val[5]);
$val_list = implode("','", $val_ids);

$result = mysql_query("INSERT into mytable(id, title, {$val_list}) 
VALUES ('$id','$title','{$f_list}')");

Where is the error, I cannot find it???

Was it helpful?

Solution

'{$f_list}' is only one value. But {$f_list} is many column identifiers. The result is not enough values to be inserted (which mysql_error() would tell you if you used it).

What you want is:

$result = mysql_query("INSERT into mytable(id, title, {$f_list}) 
VALUES ('$id','$title','{$val_list}')");

Basically you just used the wrong variable.

OTHER TIPS

Just quickly looking at your code, shouldn't be there

VALUES ('$id','$title','{$val_list}') 

instead of

VALUES ('$id','$title','{$f_list}')

what you have there now?

Try to printout value of $val_ids and $val_list to see if values are as you expect.

You can use JSON instead of php arrays, that is so easy and error free way to insert mysql.

<?php
   $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
   echo json_encode($arr);
?>

While executing, this will produce following result:

{"a":1,"b":2,"c":3,"d":4,"e":5}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top