12

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;
?>
6
  • if you are echo ing $report inside while loop , do you get any op? Commented Sep 7, 2011 at 17:09
  • 2
    PHP doesn't really have a concept of scope like, say, Java's where this would be a problem. If $report is not declared by the time you get to the echo statement, I am guessing PHP never enters the while loop in the first place. Commented Sep 7, 2011 at 17:12
  • Hmm, well it's not working. I am obviously not just trying to echo the $report, I am just posting the code this way for simplicity's sake. The only way I can use the variable outside of the loop is if I echo it first. Commented Sep 7, 2011 at 17:14
  • 1
    PS: You really shouldn't be using $row[prevDOCid]. Use quotes: $row['prevDOCid']. It might work, but it's wrong. Commented Sep 7, 2011 at 17:15
  • 1
    It gives undefined variable, that's correct. Commented Sep 7, 2011 at 17:18

1 Answer 1

19

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 +=

Sign up to request clarification or add additional context in comments.

4 Comments

@RVward You are wrong. They can be declared in the loop and be used outside of it. Here's proof. The difference is this concatenates new values to $report, instead of just overwriting it with each iteration of the loop.
@RVWard Interesting. So if you run the script exactly as it is in your question, it will tell you $report is undefined?
What result do you actually expect? Purhaps in the last loop you just override the variable with a null value...
@Vilius what if I want to access this var on the top of the while loop is it possible?

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.