Code Check: PHP/MySQL doesn't populate the option drop-down list

Can you see why the following code does not populate the drop-down list?

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><select size="3" name="chooseMagName">
<option value="">Monthly Issues:</option>
<?php
$sqlquery2 = "SELECT mag_name GROUP BY mag_name
	FROM cover_tiers
	WHERE 1=1
	ORDER BY mag_name ASC";
	
	if (!$sqlquery2) {
	die('Invalid query: ' . mysql_error()); }	

$sqlquery2 = mysql_query($sqlquery2);

while ($result2 = mysql_fetch_array($sqlquery2))
	{
	$mag_name = htmlspecialchars($result2['mag_name']);
	echo"<option value="$mag_name">$mag_name</option>\
";
	}
?>
</select></p>

I am getting the error:

Parse error: syntax error, unexpected T_VARIABLE, expecting ‘,’ or ‘;’ in /home/teamae/public_html/admin/media_tracker/v2/v2_cover_tier_home.php on line 115

Line 115 is the echo line near the end.

Thanks!

Try adding a space between echo and use single quotes. Also you should not use mysql_query, either use mysqli or [URL=“http://php.net/manual/en/book.pdo.php”]PDO. The mysql extension is no longer supported.


echo "<option value='{$mag_name}'>{$mag_name}</option>\
";

If I post it this way:

$mag_name = htmlspecialchars($result2['mag_name']);
echo "&lt;option value="$mag_name"&gt;$mag_name&lt;/option&gt;\

";

… then the error continues.

If I post it this way with . $mag_name . :

$mag_name = htmlspecialchars($result2['mag_name']);
echo "&lt;option value=" . $mag_name . "&gt;$mag_name&lt;/option&gt;\

";

… then the page displays without the error, but the $mag_name variable’s options don’t appear.

I just edited my reply, sorry for the error. You have to either use single quotes to surround the value or escape the double quotes because the doubles are closing the string. Using just the “.” operator is failing to place quotes around the value in the printed string. The following code will do what you want


echo "<option value='{$mag_name}'>{$mag_name}</option>\
"; 
// or
echo "<option value=\\"{$mag_name}\\">{$mag_name}</option>\
";
 

I copied/pasted in each of your ideas in turn, and neither one echoed the variables. No error messages, either.

Does the html structure for the options print? Put a var_dump($result2); inside your while loop and see if it prints the values.

The GROUP BY seems to be the problem. Without those two words, it will print it, but will repeat the row content as many times as it appears. I thought GROUP BY would show only one occurrence of the name. So the GROUP BY syntax is wrong somehow.

This works:

$sqlquery2 = “SELECT mag_name
FROM cover_tiers
WHERE 1=1
GROUP BY mag_name
ORDER BY mag_name ASC”;

Glad it’s working, errors with no warnings are always a pain to track down.