in my current project I want to split 10 users from a queue into 2 teams with 5 users each.
When 10 users are in the queue the function create_new_lobby() is executed. In this function the match is created and all users should be assigned to the teams in an intermediate table. With a for loop all users should be assigned to the match. Currently the for loop only takes every second user (0, 2, 4, 6, 8). The values 1, 3, 5, 7 & 9 are apparently skipped by the for loop.
Where is the error here?
<?php function create_new_lobby() { global $connection; $timestamp = date("Y-m-d H:i:s", strtotime(date('h:i:sa'))); $stmt = $connection->prepare("INSERT INTO competition_game (create_time) VALUES (?)"); $stmt->bind_param("s", $timestamp); $stmt->execute(); $stmt->close(); $stmt = $connection->prepare("SELECT competition_match_id FROM competition_game ORDER BY competition_match_id DESC LIMIT 0, 1"); $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_assoc(); $competition_match_id = $row['competition_match_id']; $stmt->close(); for($player = 0; $player <= 9; $player++) { $status_queue = 1; $stmt = $connection->prepare("SELECT * FROM competition_queue WHERE competition_queue_status = ? AND DATE_ADD(competition_queue_activity ,INTERVAL 20 MINUTE) >= NOW() ORDER BY competition_queue_id ASC LIMIT ?, 1"); $stmt->bind_param("ss", $status_queue, $player); $stmt->execute(); $result = $stmt->get_result(); while($row = $result->fetch_assoc()) { $user_id = $row['user_id']; $stmt1 = $connection->prepare("INSERT INTO competition_game_player (competition_match_id, user_id) VALUES (?, ?)"); $stmt1->bind_param("ss", $competition_match_id, $user_id); $stmt1->execute(); $stmt1->close(); } $stmt->close(); $status_leave = 2; $stmt = $connection->prepare("UPDATE competition_queue SET competition_queue_status = ? WHERE user_id = ? AND competition_queue_status = ?"); $stmt->bind_param("sss", $status_leave, $user_id, $status_queue); $stmt->execute(); $stmt->close(); } } ?>
Advertisement
Answer
The for loop works as it should and you can check that by placing an var_dump($payer)
inside the for loop;
The increment in the for loop is given by the third statement, the $player++
, which means $player = $player + 1;
If you would want to have a different looping step, you can add a different expression for the third statement in the for loop.
e.g.
for($player = 0; $player <= 9; $player++) { var_dump($player); } exit;
The code snippet will output 0 1 2 3 4 5 6 7 8 9
for($player = 0; $player <= 9; $player += 2) { var_dump($player); } exit;
The code snippet will output 0 2 4 6 8
I hope this helped you better understand the for loop.
The actual problem you are facing is created by the logic that you have made with SQL and not by the for loop