PHP prepared statements and transactions in a loop

前端 未结 1 752
不思量自难忘°
不思量自难忘° 2020-12-03 01:40

The classic transactions in a loop code:

$mysqli->query(\"START TRANSACTION\");
foreach ($pdata as $key => $value) {
    $sql    = \"INSERT INTO temp (         


        
相关标签:
1条回答
  • 2020-12-03 02:09

    Your loop can be optimized by pulling the prepare and bind_param statements out of the loop.

    $value = null;
    $mysqli->autocommit(FALSE);
    $sql  = "INSERT INTO temp (`fund_id`) VALUES (?)";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param('i', $value);
    foreach ($pdata as $value) {
        $stmt->execute();
    }
    $mysqli->commit();
    

    You have turned off autocommit with your autocommit(FALSE) line and therefore don't need to use the START TRANSACTION statement.

    0 讨论(0)
提交回复
热议问题