The while loop has beaten me up.

I run a fantasy football league.

I would like to create a page on our website that will allow people to see how each team’s wins-losses vs. all other active teams in the league.

Example where Team A has been selected:
Team A’s Record vs. Team B
Wins 2 Losses 1 Draws 0
Last game played 145.2 -132.6

TeamA’s Record vs. Team C
Wins 0 Losses 5 Draws 0
Last game played 122.3-155.6

TeamA’s Record vs. Team D
Wins 1 Losses 0 Draws 0
Last game played 143.2-115.2

so on and so on.

I have written a query and it works perfectly.

My problem is the PHP while loop. I cannot get the correct format down so that it works correctly.

Here is the query and php code:
[php]
$query = "select selected.teamname AS selected_team, selected_score.score AS selected_score, week.week, year, home_id, ".
"target_score.score as target_score, target.teamname as targetname, week.ID ".
"from owners as selected ".
"JOIN game_scores AS selected_score ON selected.owner_id = selected_score.team_id ".
"JOIN game_setup ON game_setup.game_id = selected_score.game_id ".
"JOIN game_scores AS target_score ON target_score.game_id = game_setup.game_id AND target_score.team_id != selected_score.team_id ".
"JOIN owners AS target ON target.owner_id = target_score.team_id ".
"JOIN week ON week.week = game_setup.week ".
"WHERE selected.owner_id = $thing ".
"and target.active = 1 ".
"GROUP BY target.teamname, year, week.ID ";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ’ . mysql_error());
}

$wins=0;
$losses=0;
$draws=0;
$a = ‘true’;
$b = ‘true’;

while($row = mysql_fetch_array($result))
{
if ($a = $b){
$last_target[‘targetname’] = $row[‘targetname’];
$a = ‘false’;
}
if ($last_target[‘targetname’] != $row[‘targetname’])
{
$last_target = $row;
printf(’

<table class="style1" border="1" width="400">
<tr>
	<th>Opponent Name:</th>
	<th colspan="2">%s</th>
</tr>
<tr>
	<th>Wins</th>
	<th>Losses</th>
	<th>Draws</th>
</tr>
<tr>
	<td align="center">%d</td>
	<td align="center">%d</td>
	<td align="center">%d</td>
</tr>
<tr>
	<th>Last Game:</th>
	<td colspan="2">%s of %s: %.1f - %.1f</td>
	<tr>
</table><br/>',
			$last_target['targetname'],
            $wins,
            $losses,
            $draws,
            $last_target['week'],
            $last_target['year'],
            $last_target['selected_score'],
            $last_target['target_score']
		);     
$wins = $losses = $draws = 0; 
}

if ($row[‘selected_score’] < $row[‘target_score’])
++$losses;
elseif ($row[‘selected_score’] == $row[‘target_score’])
++$draws;
else
++$wins;

$last_target = $row;
}
[/php]

I either get where the results start one row in and I get a blank box for the first result and it leaves off a team or where $last_target is always = to $row so nothing is printed to the screen.

Any help would be appreciated

Thank you for your time and effort.

Hi,

I’m not sure what you’re trying to do here:
[php]
$a = ‘true’;
$b = ‘true’;
while($row = mysql_fetch_array($result))
{ if ($a = $b) // <–(1)
{ $last_target[‘targetname’] = $row[‘targetname’];
$a = ‘false’;
}
if ($last_target[‘targetname’] != $row[‘targetname’]) <–(2)
{ $last_target = $row;
[/php]

at (1) you assign $b to $a, I assume that will be successful in most cases. This is probably not what you want ( I think you mean ‘==’ )
Before I start simplifying the while too much, why do you do what you do at (2)?

Hope it helped a little,
O.

Thank you for your reply Ojoshiro.

The reason for (1) deals with the following code:
[php]
$a = ‘true’;
$b = ‘true’;

if ($a = $b) // <–(1)
{ $last_target[‘targetname’] = $row[‘targetname’];
$a = ‘false’;
}
[/php]
When the while loop runs it doesn’t start printing to the screen until the second time through the loop. This was leaving me with results that showed a blank box on the top of the screen and left off a box at the bottom of the screen.
So I did this to try and get the results to start printing the first time though the while loop. So the first time through the loop $a will = $b that will set the previous record = to the current record then set $a to false so the second time through the loop $a will NOT = $b and the statement will be ignored.

The results of this, however, are that for the entire loop previous record is = to current record and nothing is ever printed to the screen.

The reason for number (2) deals with the following code:
[php]
if ($last_target[‘targetname’] != $row[‘targetname’])
[/php]
The idea behind this is that you take the previous record and if it is the same as the current record do the math in the while loop. IF HOWEVER the previous record and the current record are different this IF statement is used to print the results to the screen and then reset the variables back to 0.

Does this answer the questions you had?

Thank you

As I start reading the code, the first thing I notice is a long query. Yet you say that you know it works. How do you know this? I’m not being sarcastic or anything, I just need to decide whether it’s worth it for me to go through and decipher that initial mess. Thanks.

If I’m seeing this correctly it looks like your first row is equivlent to:
if ($last_target[‘targetname’] == $row[‘targetname’]) which is told never to print anything… or/

if ($last_target[‘targetname’] != $row[‘targetname’]) {
code
} else {
Looks like this is your first/missing row but there are no controls here
}

If I’m seeing this right anyway but I may not be, as I’m not really seeing the point in all the if a = b thing.

Thank you for responding and pardon me for taking so long to get back to you. Work has been hectic to say the least.

AnotherWannabe- The query works fine. I have tested it in HeidiSQL manually and it works just fine. All results are returned.

Sabmin- My theory in writing the while loop the way I did was:
Set variables. While there are rows returned do 1 of 3 things.

  1. if it is the first time thru set variables to = each other to try and get the while loop to produce the expected results. This was an attempt at a fix, not part of the original loop
  2. If the results are NOT equal it must be thru the set and should print the results and return the variables to 0
  3. If the results ARE equal the loop should continue to add up the variables set the $last_target = to the current row so it becomes the previous row and move back thru the loop.

Thanks for your time

Okay I’ve rewritten your code a couple times/ways just trying to wrap my mind around what you’re doing here, as I’ve done similiar(if not exact just under different pretense) things many times. Nothing I’ve written however leaves me sure it’s going to give you a fix and so I’ve come to the conclusion I just need a better idea of what we’re getting from the database… if you would please comment out your loop and simply put in:

$disprow = mysql_fetch_assoc($result);
print_r($disprow);

This will give me the output of everything that is retrieved in your query, so if there is any sensative information replace the values with *'s or something please. I’m not the type to do anything bad with it, but you can’t know that about me or anyone else who may view this topic so, just a precaution. :slight_smile: But once I have a better idea of/how the information is coming to us this will be easier.

edit:
Oh one more question for you… Do you have a set or max number of teams or does it vary from season to season?

I just looked up my most recent similar job, and I ended up creating a table for this, each row sepcific for a team set against each opponent, when ever a new statistic was added it adjusted the proper column

ie if you have 4 teams table would look like this:
[id][team1][team2][w][l][d][last_match]
[id][team1][team3][w][l][d][last_match]
[id][team1][team4][w][l][d][last_match]
[id][team2][team3][w][l][d][last_match]
[id][team2][team4][w][l][d][last_match]
[id][team3][team4][w][l][d][last_match]

Then say I was looking for team 2’s record vs team 1, rather than counting wins as wins(as I would if looking at team 1 vs 2) I’d call them losses while, losses wins, it was a little extra db work when adding new stats but made it much easier to navigate and lighter on resources compared to continually counting every individual match whose record was in its own table.

Thanks for all your hard work Sabmin

As per your request I put in the code you asked for and the results are:

Array ( [selected_team] => Xanadu Dragons [selected_score] => 397.4 [week] => Week 9 [year] => 2010 [home_id] => 12 [target_score] => 394.7 [targetname] => America Enforcers [ID] => 9 )

If you would like I would be happy to, if I can figure it out, private message or e-mail the webpage addy to you so you can better see what I am trying to accomplish.

As for your other question. At the moment we have a set number of 16 teams per season, however that has changed in the past and the option is open each year for a reduction in teams. I used to have a table similar to the one you mentioned, but it got so cumbersome keeping up with everything, both in the table data and the query constructs that I decided to go with the system I have now. Table for game setup, table for game scores and table for owners. Every where else this system has made the work much easier, and even here the query is fine. It is the php code that I just don’t have enough grasp on yet to make this work correctly.

I hope I have given you all the answers you are looking for and again thank you very much for your effort.

That’s the entire result?? you have something like a 300ish character query for 1 row? Sorry I’m just wondering if this is being overcomplicated some how, I’ll look at the query and give a real response shortly. :slight_smile:

My apologies Sabmin, I must not have done exactly what you wanted.
The query can return up to 797 rows in that format. However one of the variables in the query is to pick the owner_id, this will limit the number of games played to that person. For example my team has played 55 games vs. active teams, while a team that just started last year played 15 games vs. active teams.

What I did was:
[php]
$disprow = mysql_fetch_assoc($result);
print_r($disprow);

/*
while($row = mysql_fetch_array($result))
{
if ($a = $b){
$last_target[‘targetname’] = $row[‘targetname’];
$a = ‘false’;
}
if ($last_target[‘targetname’] != $row[‘targetname’])
{
$last_target = $row;
printf(’

Opponent Name: %s
Wins Losses Draws
%d %d %d
Last Game: %s of %s: %.1f - %.1f

', $last_target['targetname'], $wins, $losses, $draws, $last_target['week'], $last_target['year'], $last_target['selected_score'], $last_target['target_score'] ); $wins = $losses = $draws = 0; } if ($row['selected_score'] < $row['target_score']) ++$losses; elseif ($row['selected_score'] == $row['target_score']) ++$draws; else ++$wins; $last_target = $row; } */ [/php]

But since I did not get the results you wanted, I am thinking I should have done:
[php]
while($row = mysql_fetch_array($result))
{
$disprow = mysql_fetch_assoc($result);
print_r($disprow);
/*
blah blah blah
*/
}
[/php]

Again I am sorry for that.

I went and re-ran the query in the way I think I should have to begin with for the team that just started last year and here are those results.

Array ( [selected_team] => Wild Barbarians [selected_score] => 347.8 [week] => Week 3 [year] => 2011 [home_id] => 15 [target_score] => 418.7 [targetname] => Camelot Fluffy Butts [ID] => 3 ) Array ( [selected_team] => Wild Barbarians [selected_score] => 375.1 [week] => Round 3 [year] => 2011 [home_id] => 13 [target_score] => 316.4 [targetname] => Epic Fail [ID] => 24 ) Array ( [selected_team] => Wild Barbarians [selected_score] => 374.6 [week] => Week 8 [year] => 2011 [home_id] => 15 [target_score] => 414.0 [targetname] => Haku's Herps [ID] => 8 ) Array ( [selected_team] => Wild Barbarians [selected_score] => 293.2 [week] => Week 12 [year] => 2011 [home_id] => 15 [target_score] => 341.0 [targetname] => Knee Wrecker [ID] => 12 ) Array ( [selected_team] => Wild Barbarians [selected_score] => 457.6 [week] => Week 14 [year] => 2011 [home_id] => 8 [target_score] => 338.8 [targetname] => Pink Panthers [ID] => 14 ) Array ( [selected_team] => Wild Barbarians [selected_score] => 330.8 [week] => Week 9 [year] => 2011 [home_id] => 9 [target_score] => 360.0 [targetname] => San Fransico Wizards [ID] => 9 ) Array ( [selected_team] => Wild Barbarians [selected_score] => 304.9 [week] => Week 6 [year] => 2011 [home_id] => 15 [target_score] => 278.7 [targetname] => Xanadu Dragons [ID] => 6 )

Sorry, been a busy busy weekend and I’m still running at 100mph, give this a try

[php]<?php
$query = "select selected.teamname AS selected_team, selected_score.score AS selected_score, week.week, year, home_id, ".
"target_score.score as target_score, target.teamname as targetname, week.ID ".
"from owners as selected ".
"JOIN game_scores AS selected_score ON selected.owner_id = selected_score.team_id ".
"JOIN game_setup ON game_setup.game_id = selected_score.game_id ".
"JOIN game_scores AS target_score ON target_score.game_id = game_setup.game_id AND target_score.team_id != selected_score.team_id ".
"JOIN owners AS target ON target.owner_id = target_score.team_id ".
"JOIN week ON week.week = game_setup.week ".
"WHERE selected.owner_id = $thing ".
"and target.active = 1 ".
"GROUP BY target.teamname, year, week.ID ";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ’ . mysql_error());
}
while($row = mysql_fetch_assoc($result))
{
if (!isset($t1)) { // Assign the team we’re looking up
$t1 = $row[‘selected_team’];
}
if (!in_array($row[‘targetname’], $t2)) { //create array of all opponents
$t2[] = $row[‘targetname’];
}
foreach ($t2 as $k => $v) { // get the array key of the opponent we are working with in this…
if $v = $row[‘targetname’] { // …instance of this loop
$key = $k;
}
}
// create array of scores, and last meeting using team $k as identifier
if ($row[‘selected_score’] < $row[‘target_score’]) {
$records[$key][‘losses’] = ($records[$key][‘losses’] + 1);
}
if ($row[‘selected_score’] == $row[‘target_score’]) {
$records[$key][‘draws’] = ($records[$key][‘draws’] + 1);
}
if ($row[‘selected_score’] > $row[‘target_score’]) {
$records[$key][‘wins’] = ($records[$key][‘wins’] + 1);
}
$records[$key][‘met’] = ("Last played on week " . $last_target[‘week’] . " of " . $last_target[‘year’] . “. With a score of: " . $last_target[‘selected_score’] . " to " . $last_target[‘target_score’]);
}
$num = count($records);
for ($i=0; $i<=$num; $i++) {
$t2 = $t2[$i];
$w = $records[$i][‘wins’];
$l = $records[$i][‘losses’];
$d = $records[$i][‘draws’];
$m = $records[$i][‘met’];
echo (”

" . $t1 . "














Opponent:

" . $t2 . "

Wins: " . $w . "
Losses: " . $l . "
Draws: " . $d . "

" . $m . "

");
}
?>[/php]

Wow thank you Sabmin and no worries about a busy weekend, I totally understand.

I have put your while loop in place of mine and got an error. I have tried looking into it, but have had little luck with a fix.

The error is:
Warning: in_array() [function.in-array]: Wrong datatype for second argument in /home/content/75/6666575/html/completeownerstats.php on line 1883

it refers to the following lines:
[php]if (!in_array($row[‘targetname’], $t2)) { //create array of all opponents
$t2[] = $row[‘targetname’];
[/php]

Now I just need a week or two to try and learn what you have done.

Again thank you very much

basically that is saying $t2 isn’t an array… yet… I assume its working fine aside from the error? as its not a fatal error which is why it says warning, you can fix it by putting $t2 = array(); before the loop starts.

As much as this pains me to say, and believe me I have tried very hard to not have to say this, it still is not working right.

I am sorry Sabmin, if it is my inability to do what you have so graciously told me, well needless to say this sucks.

Ok there are four errors here.

First up in our selected_team array the first team is put on the screen the second team is just “m” (and I don’t know where it got m. Really the letter m is not even put in the code around $t2 anywhere) and all other selected_team places are blank

Second up is that Draws all come out blank instead of 0

Third

“. $m .” produces the hard coded text, but none of the variables are produced.

Lastly there is an empty set at the bottom

I have tried to check all the syntax and spelling of the column names, and all of it looks good.
I have placed the $t2 = array(); as you suggested.

Once again Sabmin thank you very much for all your work and effort in this.

I can only bebrief and not give too good of answers as I only have my phone at the moment… for draws. And really all stats do anull check on the variable before sending it to browser… if x == ‘’ then x = 0… as far as the phantm m I believe you answered that problem yourself… there’s very likely not a syntax error, but problem till arund that $m… ill take alook at it tonigt though so we can get to the bottom of the problems. :slight_smile:

Sabmin you are very uber,

I followed what you said and fixed the second error.

Second up is that Draws all come out blank instead of 0
It was making wins, losses and draws all blank when Null, not just Draws like I first thought.

I inserted:
[php]
if ($w=== NULL){$w=0;}
else{$w;}
if ($l=== NULL){$l=0;}
else{$l;}
if ($d=== NULL){$d=0;}
else{$d;}
[/php]
And it populates blank spots with the 0. I will have to do a manual check tomorrow on the actual stats, but I think that has fixed that problem.

I looked again and really don’t see the problem that would ever make $t2 = m

copy & paste error on the last match code

for the empty one at the bottom, should it be there? or are all of the teams accounted for and we’re just adding a space for a team that doesn’t exist? if that’s the case for ($i=0; $i<=$num; $i++) { change the $i to equal 1 instead of 0.

Also it never ceases to amaze me that I still make this mistake, in the for loop we kill the t2 array of opponents

try this and see if it fixes everything
[php]<?php
$query = "select selected.teamname AS selected_team, selected_score.score AS selected_score, week.week, year, home_id, ".
"target_score.score as target_score, target.teamname as targetname, week.ID ".
"from owners as selected ".
"JOIN game_scores AS selected_score ON selected.owner_id = selected_score.team_id ".
"JOIN game_setup ON game_setup.game_id = selected_score.game_id ".
"JOIN game_scores AS target_score ON target_score.game_id = game_setup.game_id AND target_score.team_id != selected_score.team_id ".
"JOIN owners AS target ON target.owner_id = target_score.team_id ".
"JOIN week ON week.week = game_setup.week ".
"WHERE selected.owner_id = $thing ".
"and target.active = 1 ".
"GROUP BY target.teamname, year, week.ID ";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ’ . mysql_error());
}
while($row = mysql_fetch_assoc($result))
{
if (!isset($t1)) { // Assign the team we’re looking up
$t1 = $row[‘selected_team’];
}
if (!in_array($row[‘targetname’], $t2)) { //create array of all opponents
$t2[] = $row[‘targetname’];
}
foreach ($t2 as $k => $v) { // get the array key of the opponent we are working with in this…
if $v = $row[‘targetname’] { // …instance of this loop
$key = $k;
}
}
// create array of scores, and last meeting using team $k as identifier
if ($row[‘selected_score’] < $row[‘target_score’]) {
$records[$key][‘losses’] = ($records[$key][‘losses’] + 1);
}
if ($row[‘selected_score’] == $row[‘target_score’]) {
$records[$key][‘draws’] = ($records[$key][‘draws’] + 1);
}
if ($row[‘selected_score’] > $row[‘target_score’]) {
$records[$key][‘wins’] = ($records[$key][‘wins’] + 1);
}
$records[$key][‘met’] = ("Last played on week " . $row[‘week’] . " of " . $row[‘year’] . “. With a score of: " . $row[‘selected_score’] . " to " . $row[‘target_score’]);
}
$num = count($records);
for ($i=1; $i<=$num; $i++) { // change $i to equal 1 instead of 0, should prevent empty
// last space… just make sure this isn’t a false fix and that
// all teams are accounted for.
$team2 = $t2[$i]; //changed the name of this variable so we don’t kill the array and changed it below to match
$w = $records[$i][‘wins’];
$l = $records[$i][‘losses’];
$d = $records[$i][‘draws’];
$m = $records[$i][‘met’];
echo (”

" . $t1 . "














Opponent:

" . $team2 . "

Wins: " . $w . "
Losses: " . $l . "
Draws: " . $d . "

" . $m . "

");
}
?>[/php]

Greetings all powerful Sabmin,

I have placed the fixes that you recommend and three of the four issues are fixed. The only issue that is left is the displaying of the last match-ups.

There is no error message displayed.

All it prints to the screen is
“Last played on week of. With a score of: to”

So as you can see it is not printing the variables to the screen. Instead of:
Last played on week $row[‘week’] of $row[‘year’]. With a score of $row[‘selected_score’] to $row[‘target_score’]

I really owe you some cookies after all the work you have put in. Thanks a bunch!!!

so it works on all matches except the last one?

Sponsor our Newsletter | Privacy Policy | Terms of Service