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

前端 未结 5 2061
庸人自扰
庸人自扰 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:28

    OPTION 1 You can actually run multiple queries at once.

    $queries = '';
    
    foreach(){
        $queries  .= "INSERT....;";  //notice the semi colon
    }
    
    mysql_query($queries, $connection);
    

    This would save on your processing.

    OPTION 2

    If your insert is that simple for the same table, you can do multiple inserts in ONE query

    $fruits = "('".implode("'), ('", $fruitsArray)."')";
    mysql_query("INSERT INTO Fruits (Fruit) VALUES $fruits", $connection);
    

    The query ends up looking something like this:

    $query = "INSERT INTO Fruits (Fruit)
      VALUES
      ('Apple'),
      ('Pear'),
      ('Banana')";
    

    This is probably the way you want to go.

提交回复
热议问题