<?php
include('functions.php');

$query = "SELECT max(sort) FROM praemienliste WHERE praemientyp = 'O18'";
$result = dbQuery($query) or error(dbError());
$row = dbFetchRow($result);
dbFreeResult($result);
$maxsort = $row[0] +1;
print "Maxsort: $maxsort\n";

$query = "SELECT * FROM praemienliste WHERE praemientyp = 'U18'";
$result = dbQuery($query) or error(dbError());

while ($row = dbFetchRow($result, MYSQL_ASSOC)) {
  $praemienId = $row['praemienId'];
  $sort = $row['sort'];
  $subquery = "SELECT praemienId FROM praemienliste
               WHERE praemientyp = 'O18'
               AND praemienId = '$praemienId'";
  $subresult = dbQuery($subquery) or error(dbError());
  if (dbNumRows($subresult) == 0) {
    $subquery = "INSERT INTO praemienliste
                 SET praemienId = '$praemienId',
                 praemientyp = 'O18',
                 sort = $maxsort";
    $subresult = dbQuery($subquery) or error(dbError());
    $maxsort++;
  }
}
dbFreeResult($result);

