while loop missunderstanding

Discussion in 'PHP' started by stats, May 27, 2007.

  1. #1
    please someone explain me this:

    suppose i have an sql tabl containing 1 column "ID" and right now i have 5 entries in there like this:
    a_1
    a_2
    a_4
    a_5
    a_6

    i want to list all available id's up to a_10 .

    so i wrote like this:

    
    $query = mysql_query('select * from table');
    for ($i = 1; $i <= 10; $i++) {
    $index = "a_"."$i"
    while ($line = mysql_fetch_array($query)) {
    if ($line['id'] == $index) {
    echo "$index <br>";
    }
    }
    }
    
    Code (markup):
    I expected this should construct a_1 and go trough the while loop and if there is a_1 then list it, then it should construct a_2 and go trough the while loop again and list it, etc ..

    however, the reality is that it constructs a_1 and go trough while loop, then constructs a_2 and NEVER go to while loop again .. so it goes trough the while loop only 1 time and that's all ..

    after long trial and failure, i have come up with this code which works
    
    $query = mysql_query('select * from table');
    for ($i = 1; $i <= 10; $i++) {
    $index = "a_"."$i"
    while ($line = mysql_fetch_array($query)) {
    if ($line['id'] == $index) {
    echo "$index <br>";
    break;
    }
    }
    }
    
    Code (markup):
    (so i just added a "break;" in the "if" statement)

    now, i still really don't understand what did i do .. why does the thing not want to go trough the "while" loop for each cyle of "for" loop ? is it because of the nature of "while" or because i use the mysql_fetch_array in "while" ? or maybe because of something else ?

    can someone please explain me what hapened, and why did the "break;" command in the "if" loop solve the situation ? .. i did it, but i still don't understand ..

    Thanks
     
    stats, May 27, 2007 IP
  2. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #2
    
    <?php
    mysql_connect('localhost', 'root', '' );
    mysql_select_db( 'mysql' );
    
    function up_to_int_from_index( $int, $index = 'a_' )
    {
     	$count = 0 ;
    	$returns = array( );
    	
    	if( !( $result = mysql_query( 'SELECT * FROM `help_keyword`' ) ) )
    	{
    		return !die( mysql_error( ) );
    	}	
    	else
    	{
    		while( $array = mysql_fetch_assoc( $result ) and $count <= $int )
    		{	
    		 	// your condition here
    		 	$returns[] = $array ;
    			$count++;
    		}
    	}
    	return $returns[0] ? $returns : false ;
    }
    
    foreach( up_to_int_from_index( 20 ) as $database )
    {
    	echo "<pre>";
    	print_r( $database );
    	echo "</pre>";
    }
    ?>
    
    PHP:
    There is no need for two loops, you are already looping use that loop to count up to the index you wanna include as the code does above .....
     
    krakjoe, May 27, 2007 IP
  3. streety

    streety Peon

    Messages:
    321
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The reason for this is that it cycles through the entire results set the first time around. When you go to the while loop a second time you're already at the end of the result set and so the while loop is skipped.
     
    streety, May 27, 2007 IP
  4. stats

    stats Well-Known Member

    Messages:
    586
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    110
    #4
    yes, that's my best guess too ..

    however, could you please explain me why did the "break;" solve my problem ? does "break;" reset the while loop to the begining or what ? i really have missunderstanding about what exactly the "break;" does in this case.

    Thanks
     
    stats, May 27, 2007 IP
  5. stats

    stats Well-Known Member

    Messages:
    586
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    110
    #5
    Thanks for this one, but i'm having hard time understanding it :) i'm kinda very noob yet and need to look at this code for a long time to understand it i guess ..

    if you could, it would be nice to see this with in-line explanations :)

    Thanks!

     
    stats, May 27, 2007 IP
  6. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #6
    
    function up_to_int_from_index( $int, $index = 'a_' )
    {
     	// count how many times we loop, it's no good to rely on ids as one or more may be missing in consecutive order
        $count = 0 ;
        // we'll store the return array here
        $returns = array( );
        // query the database, I just used the mysql one, because its the only one available to me right now
        if( !( $result = mysql_query( 'SELECT * FROM `help_keyword`' ) ) )
        {
         	// there is an error with the query, so return false and die
            return !die( mysql_error( ) );
        }   
        else
        {	
          	// the query succeeded, so loop over an associative array of the database
          	// while count ( the number of times we looped ) is smaller than or equal to int
          	// the number of rows you want to retrieve, specified when the function is called
            while( $array = mysql_fetch_assoc( $result ) and $count <= $int )
            {   
                // heres the bit you have to do, it will contain whatever conditions you
                // have in place to detect wether you would like to return the data
                $returns[] = $array ;
                // increment the counter
                $count++;
            } // end while()
        }
        // if the return array has at least one result in it, then return it else return false.
        return $returns[0] ? $returns : false ;
    }
    
    PHP:
    Hows that ??
     
    krakjoe, May 27, 2007 IP
  7. stats

    stats Well-Known Member

    Messages:
    586
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    110
    #7
    Thanks!
    will try to work it out :)
     
    stats, May 28, 2007 IP
  8. coderlinks

    coderlinks Peon

    Messages:
    282
    Likes Received:
    19
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Hello,
    If I got you right, you dont want to limit the number of rows you get. But you want to get all index values under a specified number. So suppose you have

    a_1
    a_4
    a_6
    a_10
    a_20
    a_7

    in the table, you need to get only those whose numerical parts are below than 10 or some other number. That way you should get only

    a_1
    a_4
    a_6
    a_7
    a_10

    If thats what you want, here is the code for that. This also sorts the array in the end.
    
    
    <?php
    function getUpToLimit($limit,$index = 'a')
    {
    	$res = mysql_query("SELECT * FROM help_keywords");
    	if(!$res)die(mysql_error());
    
    	$res_arr = array();
    
    	while(($data = mysql_fetch_array($res))!=FALSE)
    	{
    		list($row_index,$row_num) = explode("_",$data[0]);
    		if($row_index == $index && $row_num <= $limit)
    		{
    			array_push($res_arr,$data[0]);
    		}
    	}
    	usort($res_arr,"cmp");
    	return $res_arr;
    }
    // Compare function used by usort
    function cmp($a,$b)
    {
    	list($a_ind,$a_num) = explode('_',$a);
    	list($b_ind,$b_num) = explode('_',$b);
    	
    // Return the difference
    // It should be less than zero if a < b , equal to zero if a = b and greater than 0 if a > b
    	return ($a_num - $b_num);
    }
    ?>
    
    PHP:
    If you dont want to include the limit value, just change:
    
    $row_num <= $limit
    
    PHP:
    to
    
    $row_num < $limit
    
    PHP:
    I hope thats what you were asking for.

    ~
    Thomas
     
    coderlinks, May 29, 2007 IP
  9. stats

    stats Well-Known Member

    Messages:
    586
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    110
    #9
    Thanks guys for the coding. I am just learning php and i'll probably stick with my code as of yet since it works and i don't want to mess it up :)

    although i see your code is much better, but right now i'm just trying to make the things work only, and not "work great" :) so i'm afraid of changing anything that works

    however, i'm still wondering to know what did the "break;" command exactly do in my original code ? why did it help me ?

    and why was the "while" looping only one time and not reseting its value ? once it goes trough the array and reaches the end of the array, it does not reset the pointer to the begining so it never goes to the while loop again .. so now the "break;" has changed the situation .. i want to know did the "break;" reset the array's pointer to begining or did it do something else that i don't imagine ?

    Thanks
     
    stats, May 29, 2007 IP