Foreach loop help with mysql_fetch_array

I am getting the results of a query like this

$row = mysql_fetch_array($result);

It has three values fname, lname, username.

I want to construct a foreach loop that will give me acces to these names. I am trying to use it to populate the values in a select statement.

Like this:


<SELECT NAME="speaker">
<?php
foreach ($row)
{       $fname = $row["fname"];
	$lname = $row["lname"];
	$user = $row["username"];
	echo("<OPTION VALUE=\\"$user\\">$fname $lname</OPTION>");	
}	
?>

I am not sure how to construct the foreach loop to work like I want it to here. Can anyone point me in the right direction. I can only seem to find examples where you have $key=>$value but I cannot seem to find anying for a key here.


<SELECT NAME="speaker">
<?php
while ( $row = mysql_fetch_array($result))
{  echo("<OPTION VALUE=\\"".$row['username']."\\">".$row['fname']." ".$row['lname']."</OPTION>");
}
?>
</SELECT>


You shouldnt try to use a foreach loop for this type of thing.


while ($data = mysql_fetch_array($result))
{
    foreach($data as $key => $var)
    {
        echo $key . ' = ' . $var . '<br />';
    }
    echo '<hr />';
}

The above is a more acceptable usage, the while loop loops through the query result rows, and the foreach loop extracts all the row entries.

You could try:


$query = mysql_query("SELECT * FROM tbl_speakers");

echo "<select name='speaker' size='1'>";

while($avar = mysql_fetch_array($query))
{
    echo "<option value='". $avar['user'] ."'>". $avar['fname'] ." ". $avar['lname'] ."</option>";
}

echo "</select>";

I see the error in my logic here. I guess I have just gotten to love foreach loops to much. =)

It seems to be going better using the while but I am getting an error:

Parse error: parse error, unexpected T_ECHO in /var/www/html/psych_eval/add_new_date.php on line 81

where 81 is the echo line:

echo("<OPTION VALUE=\\"" . $row['username'] . "\\">" . $row['fname'] . " " . $row['lname'] . "</OPTION>");____

Maybe I have been looking at this stuff to long, but I fail to see what is wrong. Any fresh eyes out there?

whats the line before that? did you end the line with a semicolon

<SELECT NAME="speaker">
			<?php
				while ($row_=_mysql_fetch_array($result))
				{
					echo("<OPTION VALUE=\\"" . $row['username'] . "\\">" . $row['fname'] . " " . $row['lname'] . "</OPTION>");
				}_
			?>
			</SELECT>	

is the whole block

The previous line is a ways up and is this:

if (!($result = @ mysql_query($query, $connection)))
		showError();
	

// now that we have a list of the speakers we can display the form

?>

never mind, must have been some kind of spacing issue. I cleaned up the code a bit to make it prettier and suddenly it seems to work.