Comma lists into drop down with PHP and MySQL

Is it possible to add a database list ie L, M, N, O dynamically into a drop down menu?

I have attached a couple of images to show what i mean.
Picture-1.png
Picture-3.png
BrighteyesDesignAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

john-formbyCommented:
Hi,

You can do it like this.

Hope this helps,

John
<?php
$list = 'L,M,N,O';
$listarray = explode(',',$list);
echo '<select name="size">
	<option value="all">All</option>';
	foreach($listarray as $value) {
		echo '<option value="'.$value.'">'.$value.'</option>';
	}
echo '</select>';
?>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Cornelia YoderArtistCommented:

$string="L,M,N,O";
$array = explode(",", $string);

Then populate the dropdown from the $array elements using foreach() or similar array function.
0
BrighteyesDesignAuthor Commented:
Thanks for that,.

Just one thing though 'L,M,N,O' needs to be dynamic as there are different sizes for some products (even though the screenshot i attached typically showed two entries both with L,M,N,O!)

I have tried replacing 'L,M,N,O' with 'size' and '$size' but that does not seem to work.

Any ideas?
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

john-formbyCommented:
The code I posted was an example since I don't have the database.

Please have a look at the following example.  I have posted the MySQL table for reference.

Hope this helps,

John
page.php
========
<?php
$dbHost = "localhost";
$dbUser = "YOUR_USERNAME";
$dbPass = "YOUR_PASSWORD";
$dbName = "YOUR_DATABASE";
$db = mysql_connect($dbHost,$dbUser,$dbPass);
mysql_select_db($dbName,$db);

$query = mysql_query("SELECT * FROM tblitem") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
	echo 'ID: '.$row['id'].', Item: '.$row['item'].' ';
	$list = $row['size'];
	$listarray = explode(',',$list);
	echo '<select name="size">
		<option value="all">All</option>';
		foreach($listarray as $value) {
			echo '<option value="'.$value.'">'.$value.'</option>';
		}
	echo '</select><br />';
}
?>




tblitem
=======
CREATE TABLE `tblitem` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `item` varchar(50) NOT NULL,
  `size` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `tblitem`
--

INSERT INTO `tblitem` (`id`, `item`, `size`) VALUES
(1, 'Item 1', 'L,M,N,O'),
(2, 'Item 2', 'A,B,C,D');

Open in new window

0
Cornelia YoderArtistCommented:
If your string is anything (including a php variable) that is alphanumeric characters separated by commas, it will work.

$x="x";
$y="yyy";

$string = "L,M,$x,$y,ZZZ";
$array = explode(",",$string);

$array will then have 5 elements -- L  M  x  yyy  ZZZ

0
BrighteyesDesignAuthor Commented:
Thanks again,

Sorry to be a apin but if i copy my pages code could you see where i'm going wrong?

The table where the product info resides is 'products' the recordset is 'rs_items' and the column is called size.

Also, here's a link to the site http://www.leylasbijoux.com/jewellery.php

Just click on any ring and you'll see the blank dropdown where the sizes should show.

Again, thanks for your patience!!!!!!!

<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}



mysql_select_db($database_Leyla, $Leyla);
$query_rs_style = "SELECT * FROM ringstyle";
$rs_style = mysql_query($query_rs_style, $Leyla) or die(mysql_error());
$row_rs_style = mysql_fetch_assoc($rs_style);
$totalRows_rs_style = mysql_num_rows($rs_style);

mysql_select_db($database_Leyla, $Leyla);
$query_rs_colour = "SELECT * FROM colour";
$rs_colour = mysql_query($query_rs_colour, $Leyla) or die(mysql_error());
$row_rs_colour = mysql_fetch_assoc($rs_colour);
$totalRows_rs_colour = mysql_num_rows($rs_colour);

mysql_select_db($database_Leyla, $Leyla);
$query_rs_size = "SELECT * FROM ringsize";
$rs_size = mysql_query($query_rs_size, $Leyla) or die(mysql_error());
$row_rs_size = mysql_fetch_assoc($rs_size);
$totalRows_rs_size = mysql_num_rows($rs_size);

$colname_rs_items = "-1";
if (isset($_GET['id'])) {
  $colname_rs_items = $_GET['id'];
}
mysql_select_db($database_Leyla, $Leyla);
$query_rs_items = sprintf("SELECT * FROM products WHERE id = %s", GetSQLValueString($colname_rs_items, "int"));
$rs_items = mysql_query($query_rs_items, $Leyla) or die(mysql_error());
$row_rs_items = mysql_fetch_assoc($rs_items);
$totalRows_rs_items = mysql_num_rows($rs_items);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Cocktail Rings, Earings, Bracelets &amp;  Jewellry</title>
<script src="Scripts/swfobject_modified.js" type="text/javascript"></script>
<link href="leyla.css" rel="stylesheet" type="text/css" />
</head>

<body>
<table width="900" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td align="center"><img src="images/leya-logo.jpg" width="300" height="100" alt="Leya Bijoux Logo" /></td>
  </tr>
  <tr>
    <td align="center"><table width="209" height="10" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td><!-- saved from url=(0014)about:internet -->
            <div id='menu' style='display:none;'>
              <div><a href='index.html'>HOME</a></div>
              <div><a href='jewellery.php'>RINGS</a></div>
              <div><a href='bracelets.php'>BRACELETS</a></div>
              <div><a href='earrings.php'>EAR RINGS</a></div>
              <div><a href='necklaces.php'>NECKLACES</a></div>
              <div><a href='bangles.php'>BANGLES</a></div>
              <div><a href='about.php'>ABOUT LEYLA</a></div>
              <div><a href='faqs.php'>FAQ%5C%27S</a></div>
              <div><a href='contact.php'>CONTACT</a></div>
          
          </div>
          <div id="f_source_navigation" style="position:relative; top:0px; left:0px; width:928px;">
            <!-- Don't change any part of the DIV code (Press Ctrl+Shift+F to edit) -->
            <script src='Menu/MenuScript.js' type='text/javascript'></script>
            <!-- saved from url=(0014)about:internet -->
           
            <!-- Flash Object code (EMBED tag will be generated automatically) -->
            <div id="f-source-menu" style="position:relative;" onmouseover="if(!ied){i= fdiv.style.height.indexOf('px');h=Number(fdiv.style.height.substring(0,i));fdiv.style.height=h+1+'px';}">
              <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" id="Menu" width="928" height="33" >
                <param name="movie" value="Menu/menu.swf" />
                <param name="quality" value="high" />
                <param name="wmode" value="transparent" />
                <param name="FlashVars" value="flashlet={bg_Pic_URL:'None',xml_Path:'',stretch_width_to:'928px',_TransparencyShadow:30,_removeSubDelay:500,_minSubWidth:60,_max_height:550,_removeDividers:false,showSearchField:false,searchFieldWidth:80,searchTextColor:#000000,searchFieldColor:#FFFFFF,mainSoundURL:'',clickSoundURL:'',subSoundURL:'',_mainButtonHeight:28,_menuColor:#DDDDDD,_mainFont:'Times Roman',_mainFontSize:10,_mainButtonTextColor:#5e5e5e,_mainButWidthExt:6,_mainHighlightColor:#CCCCCC,_TransparencyMain:100,_subButtonHeight:20,_subMenuColor:#FEFEFE,_subFont:'Times New Roman',_subFontSize:10,_subButtonTextColor:#333333,_subHighlightColor:#999999,_TransparencySub:100,_pos_type:'relative',_pos_centered:false,_pos_top:0,_pos_left:0,_pos_insert:'the insertion point',_file_folder:'Menu'}" />
                <noscript>
                  The <a href="http://f-source.com/">flash menu</a> provided by f-source.com. All Rights Reserved
                  </noscript>
              </object>
              <script type="text/javascript">var connected; var message="Hello!"; if (connected){ Run_f_source_menu() }else{ alert("The file MenuScript.js could not be loaded!") }</script>
            </div>
          </div></td>
      </tr>
    </table></td>
  </tr>
  <tr>
    <td><div>
      <table width="930" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td align="center"><table width="929" border="0" cellpadding="0" cellspacing="0" class="querybar">
            <tr>
              <td width="122" bgcolor="#BBCACC" class="type"><table width="109" height="18" border="0" cellpadding="0" cellspacing="0" class="type">
                <tr>
                  <td><?php echo $row_rs_items['type']; ?></td>
                </tr>
              </table></td>
              <td width="598" align="center" bgcolor="#BACACC"><form action="jewellery.php" method="get">

                <table width="560" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td width="518" align="center" valign="middle"><p class="black">Ring type 
                      <select name="style" class="black" id="style">
                        <option value="ANY" <?php if (!(strcmp("ANY", $row_rs_style['style']))) {echo "selected=\"selected\"";} ?>>All</option>
                        <?php
do {  
?>
                        <option value="<?php echo $row_rs_style['style']?>"<?php if (!(strcmp($row_rs_style['style'], $row_rs_style['style'])))  ?>><?php echo $row_rs_style['style']?></option>
                        <?php
} while ($row_rs_style = mysql_fetch_assoc($rs_style));
  $rows = mysql_num_rows($rs_style);
  if($rows > 0) {
      mysql_data_seek($rs_style, 0);
	  $row_rs_style = mysql_fetch_assoc($rs_style);
  }
?>
                      </select>
                    Colour 
                    <select name="colour" class="black" id="colour">
                      <option value="ANY" <?php if (!(strcmp("ANY", $row_rs_colour['colour']))) {echo "selected=\"selected\"";} ?>>All</option>
                      <?php
do {  
?>
                      <option value="<?php echo $row_rs_colour['colour']?>"<?php if (!(strcmp($row_rs_colour['colour'], $row_rs_colour['colour']))) ?>><?php echo $row_rs_colour['colour']?></option>
                      <?php
} while ($row_rs_colour = mysql_fetch_assoc($rs_colour));
  $rows = mysql_num_rows($rs_colour);
  if($rows > 0) {
      mysql_data_seek($rs_colour, 0);
	  $row_rs_colour = mysql_fetch_assoc($rs_colour);
  }
?>
                    </select>
                     Size 
                     <select name="size" class="black" id="size">
                       <option value="ANY" <?php if (!(strcmp("ANY", $row_rs_size['size']))) {echo "selected=\"selected\"";} ?>>All</option>
                       <?php
do {  
?>
                       <option value="<?php echo $row_rs_size['size']?>"<?php if (!(strcmp($row_rs_size['size'], $row_rs_size['size']))) ?>><?php echo $row_rs_size['size']?></option>
                       <?php
} while ($row_rs_size = mysql_fetch_assoc($rs_size));
  $rows = mysql_num_rows($rs_size);
  if($rows > 0) {
      mysql_data_seek($rs_size, 0);
	  $row_rs_size = mysql_fetch_assoc($rs_size);
  }
?>
                     </select>
                    Price Range
                    <select name="range" class="black" id="range">
                      <option value="0-50">Less than £50</option>
                      <option value="51-100">£51 - £100</option>
                      <option value="101-200">£101-£200</option>
                      <option value="201-300">£201 - £300</option>
                      <option value="300-99999999">£300 +</option>
                      <option value="0-999999999" selected="selected">All</option>
                    </select>
                    </p></td>
                    <td width="62" align="left" valign="middle"><span class="black">
                      <input name="submit" type="image" id="submit" src="images/search.png" alt="Add to Basket" />
                    </span></td>
                  </tr>
                </table>
              </form></td>
              <td width="209" bgcolor="#BACACC"><table width="237" border="0" cellpadding="0" cellspacing="0" class="checkoutbar">
                <tr>
                  <td align="right" class="black">No of items:
                      <script language="JavaScript" src="http://www.romancart.com/cartinfo.asp?storeid=50225&amp;type=1" type="text/javascript"></script>
                    Total:
                    <script language="JavaScript" src="http://www.romancart.com/cartinfo.asp?storeid=50225&amp;type=2" type="text/javascript"></script>
                    <a href="http://www.romancart.com/cart.asp?storeid=50225" class="price">Checkout</a></td>
                  <td align="right"><img src="images/bag.png" alt="checkout" width="35" height="33" border="0" usemap="#Map4" /></td>
                </tr>
              </table>
                <map name="Map4" id="Map42">
                  <area shape="rect" coords="9,4,28,29" href="#" />
                </map>
                <map name="Map4" id="Map4">
                  <area shape="rect" coords="9,4,28,29" href="#" />
                </map></td>
            </tr>
          </table></td>
        </tr>
        <tr>
          <td><table width="930" border="0" cellspacing="0" cellpadding="0">
            <tr>
              <td width="332" valign="top"><table width="390" border="0" cellspacing="0" cellpadding="20">
                <tr>
                  <td valign="top"><a href="rings.php?id=<?php echo $row_rs_items['id']; ?>""><img src="uploads/<?php echo $row_rs_items['image']; ?>" alt="" border="0" /></a></td>
                </tr>
              </table></td>
              <td width="598" valign="top"><table width="540" border="0" cellspacing="0" cellpadding="20">
                <tr>
                  <td width="230" valign="top"><table width="230" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td valign="top"><p><span class="ringname"><?php echo $row_rs_items['name']; ?></span><br />
                        <span class="detailprice">£<?php echo $row_rs_items['price']; ?></span><br />
                        <?php echo $row_rs_items['size']; ?><br />
                        <?php echo $row_rs_items['description']; ?></p></td>

                    </tr>
                    <tr>
                      <td valign="top">                        <?php
$list = $row['size'];
        $listarray = explode(',',$list);
        echo '<select name="size">
                <option value="all">All</option>';
                foreach($listarray as $size) {
                        echo '<option value="'.$size.'">'.$size.'</option>';
                }
        echo '</select><br />';



?></td>
                    </tr>
                  </table></td>
                  <td width="230">&nbsp;</td>
                </tr>
              </table></td>
            </tr>
          </table></td>
        </tr>
        <tr>
          <td bgcolor="#BBCACC">&nbsp;</td>
        </tr>
      </table>
    </div></td>
  </tr>
  <tr>
    <td><table width="410" border="0" cellpadding="10" cellspacing="0">
      <tr>
        <td class="copyright"><a href="login.php" class="small">© 2010 Leylas Design</a> : Terms &amp; conditions : Delivery</td>
      </tr>
    </table></td>
  </tr>
</table>
</body>
</html>
<?php


mysql_free_result($rs_style);

mysql_free_result($rs_colour);

mysql_free_result($rs_size);

mysql_free_result($rs_items);
?>

Open in new window

0
Cornelia YoderArtistCommented:
I see the dropdown that says Size, and it contains choices...

All
L
M
N

Is that not correct?
0
BrighteyesDesignAuthor Commented:
Hi Yoder,

It's the option on the detail page not on the menu. It's where the user selects the size they want to purchase which is why the sizes are different for each product hence the need to dynamic.

Sorry about that, should have explained!
0
Cornelia YoderArtistCommented:
OK, I see.

Is it possible that line 234 should be ..

$list = $row_rs_size['size'];


Follow that line with

echo "DEBUG1 $list";
0
Mehul_PanchalCommented:
only you have to split this database value
$value=array which is return field of size
$size=  split(",",$value);

simply you can get array after that show this array using for each


I hope useful for u.

Thanks
Mehul Panchal



0
BrighteyesDesignAuthor Commented:
Perfect, thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.