Page 1 of 1

passing variable to function

Posted: Fri Jun 11, 2010 4:45 pm
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'); 

Re: passing variable to function

Posted: Fri Jun 11, 2010 5:10 pm
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.

Re: passing variable to function

Posted: Mon Jun 14, 2010 1:26 pm
by php-webmaster
Thank you so much! That did it. For some reason I assumed that functions automatically recognize global variables.