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

前端 未结 5 2120
庸人自扰
庸人自扰 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条回答
  •  Happy的楠姐
    2021-02-06 00:47

    If you have the mysqli class, you can iterate over the values to insert using a prepared statement.

    $sth = $dbh->prepare("INSERT INTO Fruits (Fruit) VALUES (?)");
    foreach($fruits as $fruit)
    {
        $sth->reset(); // make sure we are fresh from the previous iteration
        $sth->bind_param('s', $fruit); // bind one or more variables to the query
        $sth->execute(); // execute the query
    }
    

提交回复
热议问题