4

iam having an array of items like

[item1,itmem2,item3];

i have to insert these items at a particular userId:

final results look like this

UserId ItemId

2   ||  item1 
2   ||  item2
2   ||  item3

currently iam looping through the array in php code and inserting each item one by one eg

foreach($items as $item)
{
insert into items (UserId,ItemId) value  (2,$item);
}

is it possible i can insert all entries in single query.

2
  • 1
    If the array values come from user input, make sure you properly quote them so that your script isn't vulnerable to SQL injection. Hopefully, this isn't anything new for you. Commented May 8, 2010 at 7:16
  • @outis thanx for the concern but i have already taken care of that!! Commented May 9, 2010 at 17:31

4 Answers 4

6

Yes, your query could look like this:

INSERT INTO items (UserId,ItemId)
VALUES
(2, 'item1'),
(2, 'item2'),
(2, 'item3');

You can construct that string in PHP.

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

Comments

2
// Prepare the items to be inserted
foreach($items as $item)
{
   $sString .= '(2,' . $item.'),';
}

// Remove the last char comma from the built string
$sString = substr($sString,0,-1);

$sqlQuery = "INSERT INTO items (UserId,ItemId) VALUES" . $sString;
mysql_query($sqlQuery);

Comments

2

Implode is perfect for this..

foreach($items as $item){
   $items[] = '(2,' . $item.')';
}

$q = "INSERT INTO items (userID, itemID) VALUES " . implode(', ', $items);
mysql_query($q);

See - http://php.net/manual/en/function.implode.php

Comments

1

You can pre build the query like so:

$query = "";
foreach($items as $item)
{
  $query .= "insert into items (UserId,ItemId) value  (2,$item);";
}

Most databases allow you to issue multiple commands if you separate each with a semicolon.

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.