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.

3
  • Why must you avoid a for loop? Commented Jun 7, 2011 at 5:15
  • 1 query use implode() on the array Commented Jun 7, 2011 at 5:20
  • I am trying to avoid loop to speed up the process. Because this array might contain more number of values in it. Commented Jun 7, 2011 at 5:29

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Also discussed on SO before:

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.