BlackMouse
BlackMouse

Reputation: 4552

Php - Mysql. Get players into an array and sort by time

I'm trying to create an array, and then sort the objects by time, from a mysql_query.

This is what happens:

  1. When a player has completed his turn, I update the database. I set the database variable "lastTurn" to the current time.

     $nickname = $_POST['name'];
     $lastTurn = date();
     $myTurn = NO; 
     $query ... update query
    
  2. Now I need to find out who the next player is, and send the turn to him/her.

     $query = "SELECT * FROM active_users_table WHERE match_id='12345'
    

This gives me all the player associated with the current game.

But now I don't know how to continue. I want to put all the players into an array, and then sort it after turnDate i guess, to see who the next player is. Like a poker game. I also need to check another variable in the database, "havePlayerLost", to see if he still is active in the game. If he have lost, then get the next player who is active, and with the highest turnDate.

Any advice is very appreciated.

Thanks

Upvotes: 1

Views: 132

Answers (3)

Naveen Kumar
Naveen Kumar

Reputation: 4601

try this query

$query = "SELECT * FROM active_users_table WHERE match_id='12345'
          and status !='havePlayerLost'
          order by  lastTurn Asc

Upvotes: 1

albertopriore
albertopriore

Reputation: 614

To get the player sorted try to change the query adding ' ORDER BY turnDate ASC '

 $query = "SELECT * FROM active_users_table WHERE match_id='12345' ORDER BY turnDate ASC"

For the variable "havePlayerLost" I think you can change the query too like this adding ' havePlayerLost = false '

$query = "SELECT * FROM active_users_table WHERE match_id='12345' AND havePlayerLost = false ORDER BY turnDate ASC"

Upvotes: 1

I would suggest you let MySQL/SQL do a little more work than you're doing right now. The SQL query you use to update the player, can also contain the current date / time in the right format.

player_lastTurn = NOW()

When it comes to sorting your array, I'd suggest you let MySQL handle this one aswell:

ORDER BY player_lastTurn ASC

ASCending means it will give you the oldest DateTime for that cellname within the entire database.

When you use the results of these queries and build your array using it, you're array will automatically be in the correct order.

The same applies for the "lost players", so you automatically not include them in the array when you're not loading it.

Upvotes: 1

Related Questions