Reputation: 349
I have a piece of code that looks like this:
$result = mysql_query($queryc) or die(mysql_error());
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo $row['$field'];
}
}
Say that code was in a function and I wanted to pass $field to the $row[''] how would I accomplish that?
In other words I'm attempting to use $row['$field']; and $field is defined elsewhere
Upvotes: 2
Views: 164
Reputation: 798646
Single quotes inhibit variable substitution.
echo $row["$field"];
or just
echo $row[$field];
The latter is highly recommended as it does not require PHP to parse $row["$field"]
into $row[$field]
. Saves you some microtime in each iteration.
Upvotes: 3
Reputation: 655239
Variables are not expanded in single quotes; they are only expanded in double quotes or in the heredoc syntax:
When a string is specified in double quotes or with heredoc, variables are parsed within it.
So either use double quotes or, even better, just omit them:
$row[$field]
Upvotes: 3
Reputation: 6038
suppose you have this function definition:
function foo($field) {
// from that code you have given
....
echo $row[$field]; // no need of the quotation marks around $field
....
}
Upvotes: 4
Reputation: 62384
You'd not put any quotes around $field
... like this:
echo $row[$field];
Upvotes: 4