I want to access the last row created by my while loop ( the last $var ). I've tryed something like this:
$bar= "";
while ($bar= mysql_fetch_array($foo)) {
global $bar;
}
echo $bar
Why wont that work?
I want to access the last row created by my while loop ( the last $var ). I've tryed something like this:
$bar= "";
while ($bar= mysql_fetch_array($foo)) {
global $bar;
}
echo $bar
Why wont that work?
This is happening because the last time the condition in your loop is evaluated, mysql_fetch_array returns FALSE, which is assigned to $bar. When you use it after control exits the while loop, that is the value which is echoed. To retain the last value, assign to another variable within your loop; that way, it will have the value of the last iteration before the condition evaluated to false, rather than after. For example:
$last = null;
while ($row = mysql_fetch_array($q)) {
$last = $row
}
var_dump($last)
why not:
$bar = "";
$foobar = "";
while ($bar= mysql_fetch_array($foo)) {
global $bar;
$foobar = $bar;
}
echo $bar
I'm not really sure what you are doing with that global $bar, but the fact is just assign a variable what you want it to be and it will stay the correct value at the end because it is the last time it is assigned.
There is no point of making $bar global because mysql_fetch_rows populates the $bar in the while loop. Each time the while loop runs, the contents of $bar is replaced by the next row of results from your MYSQL database and when mysql_fetch_rows has run out of rows, it fills $bar with a false boolean value.
$bar =""; // Value of $bar is "".
while ($bar = mysql_fetch_array($foo)) {
$bar // $bar is an array with a row from $foo
}
// mysql_fetch_array return false and the while loop was aborted, so we end up here
echo $bar // $bar is now false.
if you want to access all the rows that was retrieved from your database you could do something like this.
$foobar = array();
while ($bar = mysql_fetch_array($foo)) {
$foobar[] = $bar;
}
//Dostuff with $foobar, ex print_r($foobar);