passing variable to function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
php-webmaster
Forum Newbie
Posts: 2
Joined: Fri Jun 11, 2010 3:45 pm

passing variable to function

Post by php-webmaster »

Hello,

I am a php newbie and am hoping that someone may have a solution to a code issue I ran into.
I have a table with data from an SQL database and I'm using the following query:

$result = mysql_query("SELECT * FROM tableName ORDER BY id");

I have a simple for-loop that plugs in the data into a table row. The code below works just fine:

Code: Select all

$var = 'fieldName';

for ($i = 0; $i < 6; $i++) {
	$number = mysql_result($result, $i, $var);
	echo "<td"; 
	if ($number < 0) {echo " class=\"negative\"";}
	echo ">" . money_format("%= (n", $number) . "</td>";
}
Since I have many rows, I would like to use a function, rather than repeat the code each time. However, if I define a function and then call the function and feed the variable in parentheses, it will not substitute $var in mysql_result with fieldName. It will, however, substitute $result with the correct predefined SQL query. The error that I'm getting is "mysql_result(): supplied argument is not a valid MySQL result resource". (If I echo $var within the function, it recognizes it.) What am I doing wrong? Any way around this? Thanks in advance!

The code below does NOT work:

Code: Select all

function getData($var) { 
	for ($i = 0; $i < 6; $i++) {
		$number = mysql_result($result, $i, $var);
		echo "<td"; 
		if ($number < 0) {echo " class=\"negative\"";}
		echo ">" . money_format("%= (n", $number) . "</td>";
	}
}
	
getData('fieldName'); 
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: passing variable to function

Post by cpetercarter »

You use the variable $result in the function without giving it a value. You need to pass $result to the function as well as $var.
php-webmaster
Forum Newbie
Posts: 2
Joined: Fri Jun 11, 2010 3:45 pm

Re: passing variable to function

Post by php-webmaster »

Thank you so much! That did it. For some reason I assumed that functions automatically recognize global variables.
Post Reply