17

循环代码中的经典事务:

$mysqli->query("START TRANSACTION");
foreach ($pdata as $key => $value) {
    $sql    = "INSERT INTO temp (`fund_id`) VALUES (" . $value . ")";
    $result = $mysqli->query($sql);
}
$mysqli->query("COMMIT");

然后我们改为准备好的语句:

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

问题:

1)这两个代码是否相同?我在准备好的语句的第二个代码中遗漏了什么吗?

2) 是$mysqli->commit()一样的$mysqli->query("COMMIT")吗?

3)我是否需要$mysqli->query("START TRANSACTION");为准备好的语句块添加或者当我们设置时事务会自动启动autocommit(FALSE)

4

1 回答 1

33

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.

于 2013-10-01T02:38:41.397 回答