Meskipun saya masih ragu bahwa transaksi dan/atau penyisipan batch adalah solusi yang layak untuk masalah penggunaan sumber daya Anda, itu masih merupakan solusi yang lebih baik daripada menyiapkan pernyataan besar-besaran seperti yang disarankan Dave.
Cobalah ini dan lihat apakah mereka membantu.
Berikut ini mengasumsikan bahwa mode penanganan kesalahan PDO diatur untuk membuang pengecualian. Contoh:$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Jika, karena alasan tertentu, Anda tidak dapat menggunakan mode Pengecualian, Anda harus memeriksa kembalinya execute()
setiap kali dan lempar Pengecualian Anda sendiri.
Transaksi tunggal:
$sql = $db->prepare("INSERT INTO players (name, level, vocation, world, month, today, online) VALUES (:name, :level, :vocation, :world, :time, :time, :online) ON DUPLICATE KEY UPDATE level = :level, vocation = :vocation, world = :world, month = month + :time, today = today + :time, online = :online");
$db->beginTransaction();
try {
foreach ($players as $player) {
$sql->execute([
":name" => $player->name,
":level" => $player->level,
":vocation" => $player->vocation,
":world" => $player->world,
":time" => $player->time,
":online" => $player->online
]);
}
$db->commit();
} catch( PDOException $e ) {
$db->rollBack();
// at this point you would want to implement some sort of error handling
// or potentially re-throw the exception to be handled at a higher layer
}
Transaksi Batch:
$batch_size = 1000;
for( $i=0,$c=count($players); $i<$c; $i+=$batch_size ) {
$db->beginTransaction();
try {
for( $k=$i; $k<$c && $k<$i+$batch_size; $k++ ) {
$player = $players[$k];
$sql->execute([
":name" => $player->name,
":level" => $player->level,
":vocation" => $player->vocation,
":world" => $player->world,
":time" => $player->time,
":online" => $player->online
]);
}
} catch( PDOException $e ) {
$db->rollBack();
// at this point you would want to implement some sort of error handling
// or potentially re-throw the exception to be handled at a higher layer
break;
}
$db->commit();
}