why in php if a variable is defined below another variable it can't find it?

Joined
12 Feb 2006
Posts
17,643
Location
Surrey
So i have my script that does a load of checking of stuff using if, else, another if, then else, another if then else.

at the top of the page i have written the mysql connect to database, which at the end of all the if elses is called and then a load of other variables is inserted into the database.

now one of the variables, lets call it insertVar, that will be inserted into the database is below the databse connection variable as it needs to be used and then at the end something happen toit just before it is inserted.

why can the variable not be seen when it is below it? when it is above the database connection vairable it can be found but not below.
 
Can you post some code? It would help us identify the problem, it sounds like you are trying to access a variable that is out of scope to me.
 
it's not out of the scope as all there is is a load of if else, unless not being in an if statement is even out of the scope?

bascially what i got:

Code:
$serverConnect = sprintf(insert into blah values $variable 1, $vairable 2);

if 1 = 2, echo incorrect,
elseif 1=3, echo also incorrect,
elseif 1=4, echo incorret again,
else $variable 1  =  "it worked";
mysql_query($serverConnect);
 
Last edited:
If I understand your somewhat odd pseudo-code correctly, you're trying to use $variable1 in the sprintf function before you've assigned to it.
 
Yep. $serverConnect is interpreted at the start of the script, and thus uses the value of $variable1 at the start of the script, not what it is at the end of the script.
 
ah very true, some reason was thinking that the variable would created once it was called at the end and not whilst php is going down the script.

ok time to stick it in a function. thanks
 
The best thing to do would just be to declare the variable just before using it.

Generally speaking, you should declare variables as close as possible to their first use, not miles up the script where it's not clear what they're supposed to do :)
 
The best thing to do would just be to declare the variable just before using it.

Generally speaking, you should declare variables as close as possible to their first use, not miles up the script where it's not clear what they're supposed to do :)

well that was my original idea but then the serverconnect variable can be used multiple times depending on stuff so decided stick it at the top aswell as other things like $_POST variables, then gothorugh the script changing stuff as i go but atleast this way it is clear the serverconnect variable (being an important one which is unchanged) is clearly displayed and easy to find.
 
Back
Top Bottom