Axe Member
Posts : 13 Join date : 2011-04-08
| Subject: PHP variable issue with database Fri Jun 17, 2011 2:39 am | |
| I'm having trouble getting my $X $Y and $Z variables declared and usable. The mySQL information has been changed for protection, but rest assure that's all working. So here are the two functions from the code. - Code:
-
<?php function doSomething() { $con = mysql_connect("localhost","hostname","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("database", $con); $result = mysql_query("SELECT * FROM Users WHERE thisField='1'"); while($row = mysql_fetch_array($result)) { $X=$row['X']; $Y=$row['Y']; $Z=$row['Z']; thisUser(); } mysql_close($con); } function thisUser() { echo $X; echo $Y; echo $Z; } ?>
So when I execute this, nothing is echoed. Any ideas? Also, a second question for bonus points. My code has an ample amount of mysql_connect and mysql_close. Would this be more/less efficient or equal as opening from the start and not closing til the end/indefinitely? |
|
System Member
Posts : 3 Join date : 2011-05-11
| Subject: Re: PHP variable issue with database Fri Jun 17, 2011 2:40 am | |
| Variables declared inside of a function are scoped to that function. You need to declare them before you run the function or make them global. This manual page explains it pretty clearly. |
|
Axe Member
Posts : 13 Join date : 2011-04-08
| Subject: Re: PHP variable issue with database Fri Jun 17, 2011 2:41 am | |
| Ah yes, scope. I'm pretty sure the global keyword will resolve this one. Thank you |
|
Skilletrockz Super Moderator
Posts : 45 Join date : 2011-05-11
| Subject: Re: PHP variable issue with database Fri Jun 17, 2011 2:42 am | |
| or instead of using global variables, another option is to pass the row to the function and then get the data you need from it and echo it. |
|
Sponsored content
| Subject: Re: PHP variable issue with database | |
| |
|