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 s开发者_如何学JAVAame 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.
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)
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');
You can insert multiple records with one SQL query. Read following article:
- Speed of INSERT Statements
Also discussed on SO before:
- Speeding up large numbers of mysql updates and inserts
精彩评论