-1

I have a question about randomly assigning users in my database using PHP. I want to create a website where people enter the number of users in the first step and the names of these users in the second step. Then the names should be mixed up randomly and each name has been assigned a different name (which must not happen: get yourself or a person assigned twice). This website is a small project for my family. We could always use them at Christmas when we make some kind of drawing. Everyone draws a name from the participants and then gets a present for the person drawn (I don't know how it is called in English. In Germany we say “wichteln”: D). Unfortunately I don't know how to do this in PHP.

So far, in the first step I have asked how many participants there are. It then checks whether the number entered is a number between 2 and 49. In the second step the names of the participants are given. When all names are entered, a button (name = teilnehmerdetails) is clicked. Then the following is carried out:

if(isset($_POST['teilnehmerdetails'])) {
     $datetime = date("Y-m-d H:i:s");
     $date = date("Ymd");
     $time = date("His");
     $generatorid = $date . $time;
     $name = $_POST['name'];
     foreach( $name as $key => $n ) {
         $teilnehmerid = $key + 1;
         $query = "INSERT INTO member (generator_id, date, userid, name) VALUES ('$generatorid', '$datetime', '$teilnehmerid', '$n')";
         $query_conn = mysqli_query($connection, $query);
         if(!$query_conn) {
             die("Query failed" . mysqli_error($connection));
         }
         echo $teilnehmerid.". Teilnehmer: ".$n;
         echo "<br>";
     }
}

The participants are now stored in the database. Using the variable $generatorid, I can see which participants belong to the request.

How can the entered names be mixed up and assigned a new name to each one?

E.g. entered the following names: Person 1, Person 2, Person 3, Person 4

A random result is then: Person 1 has Person 3, Person 2 has Person 1, Person 3 has Person 4, Person 4 has Person 2

Dharman
  • 30,962
  • 25
  • 85
  • 135
monze
  • 3
  • 1
  • 1
    Doesn't seem to be related with a database but just a permutation – Your Common Sense Nov 11 '20 at 09:12
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Nov 11 '20 at 12:02

3 Answers3

1

Well, I am happy to get this working after not coding for over 5 months. Code has been tested at my Web host.

 // I first tried to do just a single select but I landed on rocks so I decided to do double 
 $get_member_names = mysqli_query($connection, "SELECT name FROM member");
 // Get the member names so that we can place them in an array
 $get_members = mysqli_query($connection, "SELECT * FROM member");
 // This second select will enable us to place random member names to the userids

 $member_names = array();

 $members = ''; // Initiate the variable which will display the output

 if(mysqli_num_rows($get_member_names) > 0){

    while($row_names = mysqli_fetch_array($get_member_names)){
        
        // Place now the names into the array
        $member_names[] = $row_names['name'];

    }
        
 }

 if(mysqli_num_rows($get_members) > 0){
        
        while($row_members = mysqli_fetch_array($get_members)){

            $user_id = $row_members['userid'];
            $memberName = $row_members['name']; 
                
            // Get the key for the corresponding names
            $memberName_index = array_search($memberName,$member_names);
            // Use the key to remove the current name from the names array
            unset($member_names[$memberName_index]);
                
            // Change the positions of the remaining names in the array
            shuffle($member_names);
                
            // Get the new name at position 1. You can replace 0 with say 3 if you like
            $get_the_new_position_1_name = $member_names[0];
                
            // Give the name to the userids
            $members .= $user_id . ' - ' . $get_the_new_position_1_name . '<br />';

        }
        // Display result
        echo $members;
        
 }
hans-könig
  • 553
  • 8
  • 10
  • Hey hans-könig, many thanks for your response. Your code is the solution and it definitely answers my question (and I learned a lot again). Thank you very much! – monze Nov 11 '20 at 14:46
0

Looks like you're familiar with saving and querying data from database so only thing we need to solve is permuation problem.

You have members stored in the database. So now query their names to an array (lets call it members) and assign each of them another member.

$memberSize = sizeof($members);
for ($i = 0; $i < memberSize; $i++) {
    $another = mt_rand(0, memberSize - 1);
    while($i == $another);
        $another  = mt_rand(0, memberSize - 1);

    }

    echo "Member " . $members[$i] . " has another member " . $members[$another];
}
michal.jakubeczy
  • 8,221
  • 1
  • 59
  • 63
  • @Martin They are the same function. One is an alias of the other – Dharman Nov 11 '20 at 12:03
  • Hey, thank you for your answer I built the array and inserted your code. The random assignment of names worked, but it could happen that a person was assigned more than once. hans-könig's code worked. But thank you anyway - I was able to learn a lot again today – monze Nov 11 '20 at 14:45
0
 // I first tried to do just a single select but I landed on rocks so I decided to do double 
 $get_member_names = mysqli_query($connection, "SELECT name FROM member");
 // Get the member names so that we can place them in an array
 $get_members = mysqli_query($connection, "SELECT * FROM member");
 // This second select will enable us to place random member names to the userids

 $member_names = array();

 $members = ''; // Initiate the variable which will display the output

 if(mysqli_num_rows($get_member_names) > 0){

    while($row_names = mysqli_fetch_array($get_member_names)){
        
        // Place now the names into the array
        $member_names[] = $row_names['name'];

    }
        
 }

 if(mysqli_num_rows($get_members) > 0){
        
        while($row_members = mysqli_fetch_array($get_members)){

            $user_id = $row_members['userid'];
            $memberName = $row_members['name']; 

            // Change the positions of the names in the names array
            shuffle($member_names);
            
                 // Create a name for the userids
                 if($member_names[0] != $memberName){
                  
                     $new_name = $member_names[0];
                
                 }else{
                
                     $new_name = $member_names[1];
                
                 }

            // Give the userids their corresponding new names
            $members .= $user_id . ' - ' . $new_name . '<br />';

        }
        // Display result
        echo $members;
        
 }
hans-könig
  • 553
  • 8
  • 10
  • I've just realized that the first code means one userid will be left without a name. This new code will correct that mistake. – hans-könig Nov 11 '20 at 16:24