1

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???

1
  • 1
    For troubleshooting why don't you echo out the sql statement you are trying to build or echo the mysql error? Also you are using $f_list in the values, is that intentional? Commented Apr 25, 2014 at 19:54

3 Answers 3

5

'{$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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, thats the thing with the quotes. I made it work. You were right. Everything was fine, except the wrong variable :)
Thank you, hope this'll help someone else too
1

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.

Comments

1

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.