ok so i am messing around with php trying to see what i can do to improve the way i make/do things. right now i am playing around with a query set that automatically makes the variables with the database information in it then to echo it later on when needed.

here is the code that i have all together.

$fields = array("companyname","password");
		$select = "users WHERE company_id='$company_id' and master='1'";
	$result = mysql_query("SELECT * FROM $select");
	
        while($myrow = mysql_fetch_assoc($result))
             {
				 if($fields != ''){
				 foreach ($fields as &$value) {
					 ${$value} = $myrow[$value];
				 }
				 }
				 
			 }
		
echo $companyname;
echo $password;

that works fine but when i create a function with just the $result and while loop in it and within the page i call the function it doesnt seem to let me echo out any of the variables.

Function

function query($fields, $select) {
	
	$result = mysql_query("SELECT * FROM $select");
	
        while($myrow = mysql_fetch_assoc($result))
             {
				 if($fields != ''){
				 foreach ($fields as &$value) {
					 ${$value} = $myrow[$value];
				 }
				 }
				 
			 }

	
}

calling the function

$fields = array("companyname","password");
		$select = "users WHERE company_id='$company_id' and master='1'";
		query($fields, $select);
		
echo $companyname;
echo $password;

but if i change ${$value} = $myrow[$value]; to echo $myrow[$value]; it gives me my variables


Any thoughts as to why it wont let me?

thanks in advance

Recommended Answers

All 2 Replies

No confusion... The scope of the variable $companyname and $password are inside the function query(), will not available outside the function rather you declare it as a global variables. Try to give the echo $companyname and $password statements inside the function, it will perfectly works. Then, you can understand the problem easily.
Hope, you can understand this. If still you have problem, please let me know..

and so how can i declare them as global variables. the point in the function would be to eliminate the use of coding the query every time. so i can short hand the query and then put the variables where i need within the page.

i know that if you echo the variables inside the function it will spit them out. But if i was to not put the query in a function it would work the way i want it to. im pretty good at php. but i want to be better and faster at what i do. and to be more efficient. plus i have time on my hands to tinker with new concepts.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.