Question

table players

player1

player2

player3

player4

player5

...

player100

etc

I need to select 10 unique random teams with 4 players as: 1 base and 3 pivots

Currently trying to use:

    require_once "connect_to_mysql.php"; 
    $sqlCommand = "SELECT id FROM players ORDER BY RAND() LIMIT 10"; 
    $query = mysql_query($sqlCommand) or die (mysql_error()); 
    $i =1;
    while ($row = mysql_fetch_array($query)) { 
        echo "$i Base  = ";
        echo $row['id'];
        echo "<br />";  
        echo 'Pivot';   
        echo "<br />";
        if ($i % 4 == 0)
     {
       echo '<br />';
     }
     $i++;
    } 
    mysql_close();

Result must be:

**team 1**
Base 1
Pivot 1
Pivot 2
Pivot 3

**team 2**
Base 1
Pivot 1
Pivot 2
Pivot 3

**team 3**
Base 1
Pivot 1
Pivot 2
Pivot 3

**team 4**
Base 1
Pivot 1
Pivot 2
Pivot 3

**team 5**
Base 1
Pivot 1
Pivot 2
Pivot 3

**team 6**
Base 1
Pivot 1
Pivot 2
Pivot 3
Was it helpful?

Solution

If you execute multiple queries for this, teams may overlap. It all needs to be done in a single query that selects 40 random players and then distribute them to the teams:

$nteams=$_POST['teams']; 
$nbase=$_POST['base'];
$npivots=$_POST['pivots']; 
$allplayers=$nteams*($nbase+$npivots);
require_once "connect_to_mysql.php"; 
$sqlCommand = "SELECT id FROM players ORDER BY RAND() LIMIT $allplayers";
$query = mysql_query($sqlCommand) or die (mysql_error()); 
if(mysql_num_rows($query)<$allplayers) // sanity
  die('Not enough players!');
else
  for($team=1;$team<=$nteams;$team++)
    {
    for($base=1;$base<=$nbase;$base++)
      {
      $row = mysql_fetch_array($query);
      echo "Team $team Base $base = {$row['id']}<br />";
      }
    for($pivot=1;$pivot<=$npivots;$pivot++)
      {
      $row = mysql_fetch_array($query);
      echo "Team $team Pivot $pivot  = {$row['id']}<br />";
      }
    }
mysql_close();

EDIT: Changed the code to parametrize the number of teams,base players and pivots as per your comments.

OTHER TIPS

This simple code should work :

$i = 0;
while ($row = mysql_fetch_array($query)) {
    if($i % 4 == 0) 
        echo "<BR /> Base  = " . $row['id'];
    else 
        echo " Pivot : ". $row['id'];
    $i++;
}

Greg

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top