<?php include './functions.php'; function GenerateRRtable($ItemCount, $PDO_DBconn, $TempTableName) { //Based upon excellent information found on http://www.devenezia.com/downloads/round-robin/index.html if (!($ItemCount & 1)) { $insertval = []; foreach (range(1, $ItemCount-1) as $week) { $game = [$week + 1, 1]; $insertval[] = "({$week},{$game[$week & 1]},{$game[1-($week & 1)]})"; foreach (range(1, $ItemCount/2-1) as $i) { $game = [($i+$week-1) % ($ItemCount-1) + 2, ($ItemCount-$i+$week-2) % ($ItemCount-1) + 2]; $insertval[] = "({$week},{$game[$i & 1]},{$game[1-($i & 1)]})"; } } $PDO_DBconn->exec("CREATE TEMPORARY TABLE `{$TempTableName}`(Weeknr INT NOT NULL, I1 INT NOT NULL, I2 INT NOT NULL)"); $PDO_DBconn->exec("INSERT INTO `{$TempTableName}`(Weeknr, I1, I2) VALUES ".implode(",", $insertval)); } return !($ItemCount & 1); } try { $tempTbls = []; $conn = ks_connect_general(); $conn->beginTransaction(); $conn->exec("DELETE FROM SpelersGespeeld"); $conn->exec("DELETE FROM Wedstrijden"); foreach ($conn->query("SELECT * FROM Afdelingen")->fetchAll() as $Afdeling) { $teamCount = $conn->query("SELECT COUNT(*) FROM Ploegen WHERE AfdelingNR={$Afdeling['NR']}")->fetchColumn(0); //Eventually add 1 to make it an even number $teamCount += $teamCount & 1; if ($conn->query("SELECT ID FROM Ploegen WHERE AfdelingNR={$Afdeling['NR']} AND (VolgNr<=0 OR VolgNr>{$teamCount} OR VolgNr IS NULL) LIMIT 1")->fetch()) { die("Afdeling {$Afdeling['AfdelingNaam']} - teams zijn niet goed genummerd"); } $tmpTableName = "TEMP{$teamCount}"; //Only run once for specific number of teams if (!isset($tempTbls[$tmpTableName])) { GenerateRRtable($teamCount, $conn, $tmpTableName); $tempTbls[$tmpTableName] = true; } foreach (range(1, 2) as $ronde) { $compStart = $Afdeling["CompStart{$ronde}"]; //"Rondes" do not overlap? if ($conn->query("SELECT 1 FROM Wedstrijden W INNER JOIN Ploegen P ON P.ID=W.PloegID1 WHERE P.AfdelingNR={$Afdeling['NR']} AND W.Datum>'{$compStart}' LIMIT 1")->fetch()) { die("Afdeling {$Afdeling['AfdelingNaam']} ronde {$ronde} - verhoog datum"); } $moveWk = $Afdeling["WeekVerschuif{$ronde}"]; $sequence = ($ronde&1)?[1, 2]:[2, 1]; $sql = <<<EOT INSERT INTO Wedstrijden(Datum, PloegID1, PloegID2) SELECT DATE_ADD(DATE_ADD(DATE_ADD('{$compStart}', INTERVAL ((A.WeekNr+{$teamCount}-{$moveWk}-2)%({$teamCount}-1))*7+P1.Speeldag-1 DAY), INTERVAL P1.Uur HOUR), INTERVAL P1.Minuut MINUTE), P1.ID, P2.ID FROM {$tmpTableName} A, Ploegen P1, Ploegen P2 WHERE A.I{$sequence[0]}=P1.VolgNr AND A.I{$sequence[1]}=P2.VolgNr AND P1.AfdelingNR={$Afdeling['NR']} AND P2.AfdelingNR={$Afdeling['NR']} EOT; $conn->exec($sql); } } $conn->commit(); $conn = null; echo 'Wedstrijdschema succesvol aangemaakt'; } catch (PDOException $e) { error_log("Line: {$e->getLine()}-{$e->getMessage()}"); die($e->getMessage()); } ?>