Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting array into database table in single query

Tags:

php

mysql

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.

like image 732
Praveen Prasad Avatar asked Dec 22 '22 03:12

Praveen Prasad


1 Answers

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.

like image 100
Mark Byers Avatar answered Jan 10 '23 14:01

Mark Byers