0

I want to insert an imploded array to database..

Example: $array = array('A','B','C').. after the implode, the value will be A,B,C, because I use implode(",",$array)...

Then I want to insert to database but failed, it said:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') values ('Operation Director','Operation Director','F001')

What should I do?

This is the MySQL query:

$code = $_POST['code'];
$position = $_POST['check'];
$checkok = implode(",",$position);

mysql_query("insert into checklist (check_ok,check_pos,check_code) values ('$checkok','$checkok','$code')") or die (mysql_error());
Wouter J
  • 41,455
  • 15
  • 107
  • 112
haruya
  • 63
  • 3
  • 9

4 Answers4

1

First of all, you should use PDO or mysqli and use prepared statements instead to protect against potential SQL injection attacks.

Secondly, you have a syntax error in the statement itself; the trailing comma before the first closing parenthesis.

Assuming you have configured the correct character set you could use this:

$sql = sprintf(
    "insert into checklist (check_ok,check_pos,check_code) values ('%s','%s','%s')", 
    mysql_real_escape_string($checkok), 
    mysql_real_escape_string($checkok), 
    mysql_real_escape_string($code)
);

mysql_query($sql) or die (mysql_error());
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

You have an unwanted comma in the query checklist (check_ok,check_pos,check_code,). Remove it and try with,

mysql_query("insert into checklist (check_ok,check_pos,check_code) values ('$checkok','$checkok','$code')") or die (mysql_error());
Jenz
  • 8,280
  • 7
  • 44
  • 77
  • yeah,, i did not see it..sorry .. it worked now.. – haruya Apr 28 '14 at 06:22
  • 1
    @haruya Note that you must escape your variables properly, especially since they come from `$_POST`. The answer given here is still vulnerable to SQL injection attacks. – Ja͢ck Apr 28 '14 at 06:45
0

Remove the extra comma from your query,

("insert into checklist (check_ok,check_pos,check_code,) values ('$checkok','$checkok','$code')"
                                                      ^

Waring: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Rikesh
  • 26,156
  • 14
  • 79
  • 87
0

Try adding slashes/escaping just to be safe.

$code = mysql_real_escape_string($_POST['code']);
$position = mysql_real_escape_string($_POST['check']);
$checkok = implode(",",$position);
$checkok = mysql_real_escape_string($checkok);
$ret = mysql_query("INSERT INTO checklist (check_ok, check_pos, check_code)
                    VALUES ('$checkok','$checkok','$code')");
stomo21
  • 280
  • 2
  • 5