0

I want to have each array value inside a paranthesis

$id   = $_POST['id'];
$test2 = array($id);
$id_list = implode(',', $test2);
$sql .= "INSERT INTO tmp (id) VALUES ({$id_list});";

for example: I'm performing an insert so the output of the list should be (5),(10),(15) not '5','10','15'

Any suggestions on how I can insert using an array?

  • 1
    `'(' . implode('),(', $test2) .')'` but... http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?s=1|25.1876 – AbraCadaver Dec 08 '15 at 19:22

1 Answers1

0

MySQL's extended insert syntax is

INSERT INTO sometable (...fields...) VALUES (value set #1), (value set #2), (value set #3), etc...

Note how each value set is in its own (). You're not doing that. you're just passing a bunch of values in a SINGLE () set, which means you're providing values for fields that are NOT present in the field list.

You need to do

$id_list = '(' . implode('),(', $_POST['id']) . ')';

producing

(5),(10),(15)

instead of

(5, 10, 15)

You also need to realize that you're vulnerable to sql injection attacks.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • The code you gave me produces the output (5, 10, 15). I'm having trouble getting the parenthesis in between the commas –  Dec 08 '15 at 19:52
  • then is `$_POST['id']` actually an array? e.g. your form contains multiple `` tags? because doing `array($_POST['id'])` does NOT magically split a string up into multiple values for you to implode again later. you'd need to `explode()` the string first. – Marc B Dec 08 '15 at 19:56