Page 1 of 1

Stuck in a tricky loop

Posted: Fri Oct 10, 2008 10:03 pm
by phatgreenbuds67
I have a very simple table with 4 colums: "entry_id" , "win_path", "tbl_hour", "tbl_slot". In this table I have 5 rows where "win_path" is a unique value and "tbl_slot" is a unique integer value.

I run the code below but I am not getting what I would expect. The loop runs 10 times and the idea is that it will look at the 5 rows it did find and if the number in "tbl_slot" matches the current $count value then it should do one thing but if "tbl_slot" does not match, in this case it does not exist, then do something else.

Code: Select all

 
    $query = "SELECT * FROM $tblname WHERE tbl_hour = 1";
    $content = mysql_query($query); 
    $num = mysql_num_rows($content);
        
    if ($num != 0) { 
    $count = 1;
                                                                                            
     while ($count <= 10) {
         
        mysql_data_seek($content,0);     
        while ($row = mysql_fetch_array($content)) {
         
            $exists[] = $row[tbl_slot];
                
                    if (in_array($count, $exists)) {
                                                                        
                     $path = $row["win_path"];                                                                  
                     
                     } else {
                        
                     $path = "Nothing";                                                                 
                    }
                }
            echo $count . ": " . $path;
            echo "<br />";
            $count++;
         }
    }                                                                                           
 
 

To test this I entered 5 rows with 2, 4, 6, 8, 10, in the "tbl_slot" fields thinking that would work to test both conditions. But all I get is this:

1: Nothing
2: testimage5
3: Nothing
4: testimage5
5: Nothing
6: testimage5
7: Nothing
8: testimage5
9: Nothing
10: testimage5

When I should be getting this:

1: Nothing
2: testimage1
3: Nothing
4: testimage2
5: Nothing
6: testimage3
7: Nothing
8: testimage4
9: Nothing
10: testimage5

Sombody PLEASE help me...I am at my wits end. I have no idea how to resolve this. :banghead:

Re: Stuck in a tricky loop

Posted: Fri Oct 10, 2008 10:28 pm
by kpowell
In your code, you have it running all the way through the mysql_fetch_array. So, it's always going to give you the last win_path in your table. You need to add a break after the successful if like so:

Code: Select all

while ($row = mysql_fetch_array($content)) {
    $exists[] = $row[tbl_slot];
    if (in_array($count, $exists)) {
        $path = $row["win_path"];
        break;
    } else {
        $path = "Nothing";
    }
}
That way it stops your loop when it is successful and gives you what you're looking for.