0

So, I have an array which I am combining to create an INSERT command. (No sanitizing done yet, just a proof of concept).

$namedata is the data for the "Name" field (for example "This Name") $refdata is the data for the "Ref" field (for example "43857368") $CatRefData is my array (for example, '23', '45', '2', '144')

I am formulating it as follows:

$inputdata = "'), ('".$namedata."', '".$refdata."', '";
  $data = implode($inputdata, $CatRefData);
  $result = "INSERT INTO `MyTable`('Name', 'Ref', 'Cat_Ref') VALUES ('".$data."')";

But the output comes out with the first instance of the array missing any of the additional "non-array" data, like this:

$result = INSERT INTO MyTable('Name', 'Ref', 'Cat_Ref') VALUES ('23'), ('This Name', '43857368', '45'), ('This Name', '43857368', '2'), ('This Name', '43857368', '144')

Can you see - the first instance, where the array value is '23', doesn't have any of the surrounding information.

What am I doing wrong?

1
  • i think this doesnt work with implode, so you have do do a foreach to fill your $data. Commented Jul 9, 2013 at 14:35

3 Answers 3

1

I would do it like this...

$arr = array();

foreach($CatRefData as $d) {
    $arr[] = "('".$namedata."', '".$refdata."', '".$d."')";

}

$data = implode(",",$arr);

but you should do some escaping...

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

1 Comment

Ah, "foreach"! Thanks - a great solution. Perfect! (I will be escaping each of the values before they get as far as this formula, but thank you for the advice all the same).
1

implode() only adds the join text BETWEEN values, so if you have:

$arr = array('a', 'b', 'c');
$newarr = implode('foo', $arr);

you'll end up with

afoobfooc

but you actually need

fooafoobfooc

That means you have to "prime" your query with the "join" text first:

$result = "INSERT INTO `MyTable`('Name', 'Ref', 'Cat_Ref') VALUES ('$inputData"

Comments

0

I don't think you can do this with implode only.

Try using it with array_map() , something like this:

$CatRefData = [ '23', '45', '2', '144'];
function surrounding($n)
{
     return "('something', '123', '".$n."')";
}
echo implode(", ",array_map("surrounding", $CatRefData));

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.