Changes to loop do nothing

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

volka wrote:
Citizen wrote:any ideas?
Did you try
arkady wrote:Also.. why not try spitting some debug info out from the query result to confirm that the number of rows it's detecting is in fact higher than 20?
?

You can add the function

Code: Select all

function dbg_mysql_query($query) {
	echo '<fieldset><legend>sql query</legend>', htmlentities($query), "<br />\n";
	$r = mysql_query($query);
	if (!$r) {
		echo mysql_error();
	}
	else {
		echo 'num_rows: ', mysql_num_rows($r);
	}
	echo "</fieldset>\n";
	return $r;
}
and replace all calls of mysql_query by dbg_mysql_query. Do the querries look like you have expected?
and after
Citizen wrote:The query is being executed fine... it comes up with 40+ queries and i only list 20 at a time. The thing is, no matter what i set $begin and $end to, it always displays the same 20 instead of showing 21-40 or anything.
I thought you've tried it.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

You know, feyd told you, twice, that you are not using $begin or $end, and you are not using $i. What that means is that your are looping the exact same dataset regardless of what $i, $begin or $end are. Look at this little piece of example and tell me if you can spot the error in it.

Code: Select all

<?php
$begin = 0;
$end = 35;

for ($i = $begin; $i < $end; $i++)
{
    echo '<p>I can fit inside a loop!</p>';
}
?>
You see how the vars $i, $begin and $end have absolutely nothing to do with what is displayed here? It will always be the same. Now, what if you did this...

Code: Select all

<?php
$begin = 0;
$end = 35;

for ($i = $begin; $i < $end; $i++)
{
    echo '<p>The number ' . $i . ' can fit inside a loop!</p>';
}
?>
You see how the display changes now depending on $i. See if you can use this to your advantage when fixing your code problem.
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Post by Citizen »

Ok i used your dbg code and here's the result:

http://www.gamerbio.com/arcade.php


I'm getting 40 results and it displays the first 20 fine.

Then, I want if they click page 2, for it to display results 21-40

But instead this link returns the same results:

http://www.gamerbio.com/arcade.php?begin=21



Everah wrote:You know, feyd told you, twice, that you are not using $begin or $end, and you are not using $i. What that means is that your are looping the exact same dataset regardless of what $i, $begin or $end are. Look at this little piece of example and tell me if you can spot the error in it.

Code: Select all

<?php
$begin = 0;
$end = 35;

for ($i = $begin; $i < $end; $i++)
{
    echo '<p>I can fit inside a loop!</p>';
}
?>
You see how the vars $i, $begin and $end have absolutely nothing to do with what is displayed here? It will always be the same. Now, what if you did this...

Code: Select all

<?php
$begin = 0;
$end = 35;

for ($i = $begin; $i < $end; $i++)
{
    echo '<p>The number ' . $i . ' can fit inside a loop!</p>';
}
?>
You see how the display changes now depending on $i. See if you can use this to your advantage when fixing your code problem.
I dont see how I can use $i since all I am doing is showing the results. I've read everythign i've found about loops, maybe I'm just missing something.
Last edited by Citizen on Tue Sep 19, 2006 11:17 am, edited 1 time in total.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Have you changed your code inside the loop at all?
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Post by Citizen »

I'm not sure what I'm supposed to edit.... I thought the $i loop line is what controlled what results were shown?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

The loop controls the number of things shown. What controls what is shown is the use of $i inside the array that is being looped. If all you are doing is looping through a certain number of times, that by itself does nothing for your. But if, inside that loop, you tell the output to use the loop index (the $i) then you can control what is being displayed. Post your array and the loop construct again.
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Post by Citizen »

Code: Select all

if($cat == 'random'){
	$sql1="SELECT * FROM `arcade_games` ORDER BY `title`";
}
else{

$sql="SELECT * FROM `arcade_categories` WHERE `catname` = '$cat' LIMIT 1";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
$maincat = $row["catid"];

$sql1="SELECT * FROM `arcade_games` WHERE `categoryid` = '$maincat' ORDER BY `shortname`";
}
$result1=dbg_mysql_query($sql1);
$gamenum = mysql_num_rows($result1);
if ($gamenum < 20){
	$begin = 0;
	$end = $gamenum;
}
else if ( isset($_GET['begin']) ) {
	$begin = $_GET['begin'];
	$end = $begin + 20;
}
else {
	$begin = 0;
	$end = 20;
}
for($i = $begin; $i < $end; $i++) {
	$row = mysql_fetch_array($result1);
	$shortname = $row["shortname"];
	$title = $row["title"];
	$gameid = $row["gameid"];
	$stdimage = $row["stdimage"];
	$description = $row["description"];
	$thiscat = $row["categoryid"];
	$isreverse = $row["isreverse"];

	$sql2="SELECT * FROM `arcade_categories` WHERE `catid` = '$thiscat' LIMIT 1";
	$result2=mysql_query($sql2);
	$row = mysql_fetch_array($result2);
	$tempcat = $row["catname"];

	if($isreverse == 1){
		$sql3="SELECT * FROM `arcade_highscores` WHERE `gamename` = '$gameid' ORDER BY `score` LIMIT 1";
	}
	else{
		$sql3="SELECT * FROM `arcade_highscores` WHERE `gamename` = '$gameid' ORDER BY `score` DESC LIMIT 1";
	}
	$result3=mysql_query($sql3);
	$champnum = mysql_num_rows($result3);
	if($champnum == 1){
		$row = mysql_fetch_array($result3);
		$champname = $row["username"];
		$champscore = $row["score"];
	}
	else {
		$champname = "None";
		$champscore = 0;
	}
	
	$user = $VAR[4];
	$sql4="SELECT * FROM `arcade_highscores` WHERE `gamename` = '$gameid' AND `username` = '$user' ORDER BY `score` DESC LIMIT 1";
	$result4=mysql_query($sql4);
	$row4 = mysql_fetch_array($result4);
	$scorenum = mysql_num_rows($result4);
	if($scorenum == 1){
		$yourscore = $row4["score"];
	}
	else {
		$yourscore = "None";
	}	
	echo "
			<table style='width:100%;'>
				<tr>
				<td style='width:15%;text-align:center;font-size:11pt;' class='color'>
				<a href='$VAR[0]/arcade.php?play=$gameid'><img src='/arcade/images/$stdimage' border='2'></a>
				</td>
				<td style='width:30%;vertical-align:top;font-size:11pt;' class='color'>
				<b><a href='$VAR[0]/arcade.php?play=$gameid'>$title</a></b>
				<div style='font-size:10pt;'>
				$description
				</div>
				</td>
				<td style='width:15%;text-align:center;font-size:11pt;' class='color'>
				<b>$tempcat</b><br />
				(<a href='$VAR[0]/arcade.php?cat=$tempcat'>More</a>)</td>
				<td style='width:20%;text-align:center;font-size:11pt;' class='color'>
				<b><a href='$VAR[0]/$champname'>$champname</a></b>
				<div style='font-size:10pt;'>
				With a high score of:<br />
				<b>$champscore</b>				</div>
				</td>
				<td style='width:20%;text-align:center;font-size:11pt;' class='color'>
				Your high score:
				<br />
				<b>$yourscore</b>
				<br />
				[<a href='$VAR[0]/arcade.php?highscore=$gameid'>High Scores</a>]
				</td>
				</tr>
			</table>
		";
	}
}
So will I need to scrap my system of $begin and $end?

Or should it look more like this:

Code: Select all

for($i = 0; $i < $num_rows; $i++) {
      if($i > $begin && $i < $end){
             display results that fit within begin and end
      }
}
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Ok, I changed a little bit of your code around for you. You did no error checking, so I added some die's in there (though I'd recommend a customer error handler to do that) and changed some things related to your loop. See how it runs. Then toy around with it. Then post back with questions.

Code: Select all

<?php
if ($cat == 'random') 
{
    $sql1 = "SELECT * FROM `arcade_games` ORDER BY `title`";
}
else
{
    $sql = "SELECT * FROM `arcade_categories` WHERE `catname` = '$cat' LIMIT 1";
    $result=mysql_query($sql) or die('Could not run the query for catnames: ' . mysql_error());
    $row = mysql_fetch_array($result);
    $maincat = $row["catid"];

    $sql1="SELECT * FROM `arcade_games` WHERE `categoryid` = '$maincat' ORDER BY `shortname`";
}

$result1 = mysql_query($sql1) or die ('Could not process sql1 query: ' . mysql_error());
$gamenum = mysql_num_rows($result1);

// This is for the looping construct
$game_array = array();
if ($gamenum > 0)
{
    while ($row = mysql_fetch_array($result1))
	{
	    $game_array[] = $row;
	}
}
$game_count = count($game_array);
// End loop construct stuff

$begin = 0;
$end = 20;
if ($gamenum < 20)
{
    $end = $gamenum;
}
elseif ( isset($_GET['begin']) ) 
{
    $begin = intval($_GET['begin']); // What is someone passed begin=fred in the URI?
    $end = ( ($begin + 20) < $game_count ) ? $begin + 20 : $game_count;
}

for($i = $begin; $i < $end; $i++) {
        $shortname = $game_array[$i]["shortname"];
        $title = $game_array[$i]["title"];
        $gameid = $game_array[$i]["gameid"];
        $stdimage = $game_array[$i]["stdimage"];
        $description = $game_array[$i]["description"];
        $thiscat = $game_array[$i]["categoryid"];
        $isreverse = $game_array[$i]["isreverse"];

        $sql2="SELECT * FROM `arcade_categories` WHERE `catid` = $thiscat LIMIT 1";
        $result2=mysql_query($sql2) or die('Could not run the inner loop query: ' . mysql_error());
        $row = mysql_fetch_array($result2);
        $tempcat = $row["catname"];

        if($isreverse == 1){
                $sql3="SELECT * FROM `arcade_highscores` WHERE `gamename` = '$gameid' ORDER BY `score` LIMIT 1";
        }
        else{
                $sql3="SELECT * FROM `arcade_highscores` WHERE `gamename` = '$gameid' ORDER BY `score` DESC LIMIT 1";
        }
        $result3=mysql_query($sql3);
        $champnum = mysql_num_rows($result3);
        if($champnum == 1){
                $row = mysql_fetch_array($result3);
                $champname = $row["username"];
                $champscore = $row["score"];
        }
        else {
                $champname = "None";
                $champscore = 0;
        }
       
        $user = $VAR[4];
        $sql4="SELECT * FROM `arcade_highscores` WHERE `gamename` = '$gameid' AND `username` = '$user' ORDER BY `score` DESC LIMIT 1";
        $result4=mysql_query($sql4);
        $row4 = mysql_fetch_array($result4);
        $scorenum = mysql_num_rows($result4);
        if($scorenum == 1){
                $yourscore = $row4["score"];
        }
        else {
                $yourscore = "None";
        }       
        echo "
                        <table style='width:100%;'>
                                <tr>
                                <td style='width:15%;text-align:center;font-size:11pt;' class='color'>
                                <a href='$VAR[0]/arcade.php?play=$gameid'><img src='/arcade/images/$stdimage' border='2'></a>
                                </td>
                                <td style='width:30%;vertical-align:top;font-size:11pt;' class='color'>
                                <b><a href='$VAR[0]/arcade.php?play=$gameid'>$title</a></b>
                                <div style='font-size:10pt;'>
                                $description
                                </div>
                                </td>
                                <td style='width:15%;text-align:center;font-size:11pt;' class='color'>
                                <b>$tempcat</b><br />
                                (<a href='$VAR[0]/arcade.php?cat=$tempcat'>More</a>)</td>
                                <td style='width:20%;text-align:center;font-size:11pt;' class='color'>
                                <b><a href='$VAR[0]/$champname'>$champname</a></b>
                                <div style='font-size:10pt;'>
                                With a high score of:<br />
                                <b>$champscore</b>                        </div>
                                </td>
                                <td style='width:20%;text-align:center;font-size:11pt;' class='color'>
                                Your high score:
                                <br />
                                <b>$yourscore</b>
                                <br />
                                [<a href='$VAR[0]/arcade.php?highscore=$gameid'>High Scores</a>]
                                </td>
                                </tr>
                        </table>
                ";
        }
}
?>
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Post by Citizen »

Wow! It worked... ok so I guess its question time :)

Code: Select all

$result1 = mysql_query($sql1) or die ('Could not process sql1 query: ' . mysql_error());
$gamenum = mysql_num_rows($result1);

// This is for the looping construct
$game_array = array();
if ($gamenum > 0)
{
    while ($row = mysql_fetch_array($result1))
        {
            $game_array[] = $row;
        }
}
$game_count = count($game_array);
What exactly does this do? Why do we use a 'while' to setup a variable's value?

Code: Select all

$end = ( ($begin + 20) < $game_count ) ? $begin + 20 : $game_count;
Same thing here, I've never seen code used this way before. How can we use inequalities when setting a variable's value?

Code: Select all

$shortname = $game_array[$i]["shortname"];
What is [$i] doing in this code? How does the script know to pull out only the results that we want and not the same first 20 like it did last time?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Citizen wrote:Wow! It worked... ok so I guess its question time :)
I would venture to say question time was a little while ago :wink: .
Citizen wrote:What exactly does this do? Why do we use a 'while' to setup a variable's value?
You loop through the mysql_fetch_array() call and while you are looping, you assign that array to a multi-dimensional, numerically indexed array (those are a beauty for looping with for)
Citizen wrote:

Code: Select all

$end = ( ($begin + 20) < $game_count ) ? $begin + 20 : $game_count;
Same thing here, I've never seen code used this way before. How can we use inequalities when setting a variable's value?
This is the ternary operator. It is a shortened form of an if-else statement. Basically this checks to see of the total number of games is lower than $begin + 20 (because you don't want to loop farther than your array count) and sets the end value to the appropriate amount.
Citizen wrote:

Code: Select all

$shortname = $game_array[$i]["shortname"];
What is [$i] doing in this code? How does the script know to pull out only the results that we want and not the same first 20 like it did last time?
Because you made a numerical index in your array with the while loop above. So you are saying in your for loop, when you are on index number 4, show the 4th row of the games array, when we get to 13 show the 13th row, etc. That is how you can tell your script to start at 30 and end at 50 and it will show rows 30 to 50.
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Post by Citizen »

Thanks man! I have a much better understanding of loops and arrays. Theres somethign to reading it in laymens terms that makes more sense than php.net
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

How do you suppose I can speak it so easily? I assure you, you are not the first person that has a bit of a time trying to understand the manual :wink:.
Post Reply