passing variable to function
Posted: Fri Jun 11, 2010 4:45 pm
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:
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:
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>";
}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');