vasanth.v
vasanth.v

Reputation: 213

Mysql save PHP array as each value in new field

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.

Upvotes: 1

Views: 318

Answers (3)

Naveed
Naveed

Reputation: 42143

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

Also discussed on SO before:

Upvotes: 0

KoolKabin
KoolKabin

Reputation: 17683

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');

Upvotes: 1

Tomasz Kowalczyk
Tomasz Kowalczyk

Reputation: 10467

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)

Upvotes: 6

Related Questions