Jump to content

[SOLVED] foreach loop problem


chrispos

Recommended Posts

I am trying to get one pull down menu getting the information from a database but I get three drop down menus with one name in each i am using PHP 5 and Mysql 5

$query = "SELECT * FROM `cards`";
$result = mysql_query($query) or die (mysql_error());
if (mysql_num_rows($result)>0){ 
while ($row = mysql_fetch_array($result)) {
$cid=$row[0];
$hid=$row[1];
$cards=$row[2];
$array = explode (',',$cards);
echo'<select name = "cards">';
foreach ($array as $value)
{
echo "<option value=\"$value\">
$value</option>\n";
}
echo'</select>';

}
}

i dont know why i am getting 3 drop down menus one saying mastercard the other visa and the other saying maestro when I should be getting one drop down menu with the named cards

 

Any help please?

 

 

Link to comment
https://forums.phpfreaks.com/topic/152075-solved-foreach-loop-problem/
Share on other sites

By that code you would get three drop-down menus, so it's working correctly.  The reason is you've included the echo <select> inside a while() loop, so it gets looped three times.

 

You may want to re-think your table structure though - are you only storing a single row in your table for all three cards?  You should design it so that each card has it's own row in stead of exploding a single field.

echo "from PHP $Monkeh said";

 

so your code should look something like this

 

<?php
$query = "SELECT * FROM `cards`";
$result = mysql_query($query) or die (mysql_error());
if (mysql_num_rows($result)>0)
{
echo'<select name = "cards">';
while ($row = mysql_fetch_array($result))
{
	$cid=$row[0];
	$hid=$row[1];
	$cards=$row[2];
	echo "<option value=\"$cid\">$cards</option>\n";
}
echo'</select>';
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.