Skip to content Skip to sidebar Skip to footer

Getting Variable In A Loop From Outside While 'function'

I have a while loop that assigns user ID's to a variable. The variable is an array. When I assign the variable to another in a link like this: it returns proper ID's on the click

Solution 1:

You've got a syntax goof:

for ($i = 0 ; $i <100 ; $i++ );
                              ^----

The semicolon terminates the for loop, so you're doing an empty loop. Change it to:

for ($i = 0 ; $i <100 ; $i++ )
    echo"<a href......etc....";

or better yet:

for ($i = 0 ; $i <100 ; $i++ ) {
    echo"<a href......etc....";
}

Solution 2:

while ( $row = mysqli_fetch_array($sql)) { 
    $variable[] .= $row['user_id']; //Wrong$variable[] = $row['user_id']; //Correct
}

foreach($variableas$value) {
    echo"<a href='index.php?var=$value'></a>"; // Be sure to use double quotes
}

Solution 3:

Several issues are coming into play here:

  1. $variable is defined within the scope of the while loop, so it is inaccessible outside of said loop (though PHP may let you get away with this one).
  2. You are assuming that there are precisely 100 rows (indexed 0-99) returned by performing the SQL query represented by $sql. While this may be true, it's not good practice to assume this, and you should handle however many rows are actually returned by performing that query.
  3. Perhaps most importantly, if you are truly using <a href='index.php?var=$variable[$i]'></a> in an HTML context, it will not work, as $variable[$i] is PHP code. You will need to put this in a PHP document, somewhere between the <?php and ?> tags.

Post a Comment for "Getting Variable In A Loop From Outside While 'function'"