4

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?

1
  • Not sure you understand what global does and definitely why you don't want or need it there. Remove that global line, then try print_r($bar) where you echo. If that does nothing, then your $foo query is probably returning no results. Commented Oct 9, 2012 at 23:32

4 Answers 4

5

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

By using while loop we can solve the global variable problem.First fetch the data from data base,after that we assign that fetch value in any variable to use in while loop.

$bar = "" ; 
while ($bar =mysql_fetch_array($foo)){ 
global $bar; 
$foobar = $bar;
} 
echo $bar;

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.