views:

57

answers:

5

Apologies if I should know better, but I've been struggling for quite a while with this one.

I have a mysql db with 300 rows. It contains 4 columns, "eventid", "player1", "player2", "score". In the game, player1 gives various others (player2) a score out of 100.

What I'm trying to do is show the logged in user (player1) a table of the "player2"s they have scored.

My code looks like this:

$currentuserid = 00001;

$opponent_data = mysql_query("SELECT * FROM `scores` WHERE `player1` = $currentuserid ORDER by score");

$opponent_count = mysql_num_rows($opponent_data);

    echo $opponent_count.'<br>'; // Just to test -> and it shows I have 144 entries in the array, i.e. 144 player 2's that player 1 has scored

$opponent_scores = mysql_fetch_assoc($opponent_data);

$runrows = $opponent_scores;

foreach ($opponent_scores as &$runrows);

    {
    $id = $runrows['eventid'];
    $player2 = $runrows['player2'];
    $score = $runrows['score'];


    echo $player2." got ".$score;

    echo "<br>";

    }

When I run this all I can see is

144

73 got 44

but I was hoping to see 144 rows of "player 2" got "player 2's score".

What am I doing wrong?

+9  A: 

You have a semicolon after the for-each loop; that shouldn't be there.

TheAdamGaskins
Thanks, well spotted.
Peter T
+1  A: 

It looks like there is an anomolous semi colon after the for each statement

Ergo Summary
+6  A: 

In addition: mysql_fetch_assoc will only return the pointer to your first row in the resultset. That is why you'll end up with only one row being printed.

Change your code to:

while($opponent=mysql_fetch_assoc($opponent_data)) {
     echo $opponent['player2']." got ".$opponent['score'];
}
Anzeo
Thanks so much, especially for explaining what the mysql_fetch_assoc was doing - I thought it was getting all rows.
Peter T
+2  A: 
$currentuserid = 00001;

$opponent_data = mysql_query("SELECT * FROM `scores` WHERE `player1` = $currentuserid ORDER by score");

$opponent_count = mysql_num_rows($opponent_data);

    echo $opponent_count.'<br>'; // Just to test -> and it shows I have 144 entries in the array, i.e. 144 player 2's that player 1 has scored

$opponent_scores = mysql_fetch_assoc($opponent_data);

foreach ($opponent_scores as $row);

    {
    $id = $row['eventid'];
    $player2 = $row['player2'];
    $score = $row['score'];


    echo $player2." got ".$score;

    echo "<br>";

    }
Alexander.Plutov
+1  A: 

mysql_fetch_assoc returns an associative array of a single record.

Check the docs for an example of what you should be doing: http://uk3.php.net/mysql_fetch_assoc

while ($row = mysql_fetch_assoc($opponent_scores)) {
    // var_dump($row);
}
Matt