Is it bad to put a MySQL query in a PHP loop?

前端 未结 5 2062
庸人自扰
庸人自扰 2021-02-05 23:56

I often have large arrays, or large amounts of dynamic data in PHP that I need to run MySQL queries to handle.

Is there a better way to run many processes like INSERT or

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-06 00:45

    One thing to note about jerebear's answer with multiple VALUE-blocks in one INSERT:

    It can be rather dangerous for really large amounts of data, because most DBMS have an upper limit on the size of the commands they can handle. If you exceed that with too many VALUE-blocks, your insert will fail. On MySQL for example the limit is usually 1MB AFAIK.

    So you should figure out what the maximum size is (ideally at runtime, might be available from the database metadata), and make sure you don't exceed it by spreading your lists of values over several INSERTs.

提交回复
热议问题