1

I have a PHP array like

array("Saab", "Volvo", "BMW", "Toyota");

I need to store this in a MySQL database in a way that each value is inserted into a new field and not in a same field. It can be achieved by using foreach statement and running the query inside foreach statement. But I need a more efficient way to do it in a single query.

Tomasz Kowalczyk
  • 10,472
  • 6
  • 52
  • 68
vasanth.v
  • 235
  • 3
  • 14

3 Answers3

6

Pack multiple records in your INSERT query - produce single one in a loop and then execute it at the end.

INSERT INTO tbl (is, name)
VALUES
(0, 'Ford'),
(1, 'BMW'),
(2, 'Volvo)
Tomasz Kowalczyk
  • 10,472
  • 6
  • 52
  • 68
1

you can try it using implode

insert into tablename (field1, field2, field3, field4) values('".implode("'", array(...))."');

it will produce like:

insert into tablename (field1, field2, field3, field4) values('Saab', 'Volvo', 'BMW', 'Toyota');
KoolKabin
  • 17,157
  • 35
  • 107
  • 145
0

You can insert multiple records with one SQL query. Read following article:

Also discussed on SO before:

Community
  • 1
  • 1
Naveed
  • 41,517
  • 32
  • 98
  • 131