Using a variable outside of the while loop (scope)

44,162

You could try to define the variable before the loop, e.g.

$report = "";
while ($row = mysql_fetch_array($result)) {
    $report .= "a"."b".$row["prevDOCid"]+1;
}
echo $report;

I hope this helps you!

Edit Use .= not +=

Share:
44,162
Ryan Ward
Author by

Ryan Ward

I started my programmer life as a masters level economist working as a government contractor assessing risk on imported products. I spent dozens of hours a day automating these algorithms to pull in news sources and provide me with data. Along the way, I learned a lot about microbiology -- as one would expect assessing rotting food. Now, I am a PhD student in the Department of Genetics at UW - Madison interested in developing basic tools for bioinformaticians, especially those who perform genome arithmetic.

Updated on July 27, 2020

Comments

  • Ryan Ward
    Ryan Ward almost 4 years

    Small problem regarding scope in PHP, I can't seem to call the variable $report outside of the while loop. I have tried various things, including return. This doesn't work, the only two functions that work here are if I echo the variable $report inside the loop, or if I print it. Which I do not want to do, although it solves the problem, but I don't want random gibberish on the user's screen.

    I have been looking around for the last 15 or so minutes, and I haven't seen any problems quite like this one on here.

    Any help would be appreciated.

    <?
    require "functions2.php";
    require "members.php";
    $query = "SELECT MAX(DOCid) as prevDOCid from reports";
    $result = mysql_query($query);
    
    while ($row = mysql_fetch_array($result)) {
        $prevDOCid = $row[prevDOCid];
    
    $thisDOCid = $prevDOCid+1;
    $report = "a"."b".$thisDOCid;
    
    
    }
    echo $report;
    ?>