Display Records In A Drop Down Menu Combo Box From A Column Of A Table In PHP


$con = mysql_connect('localhost','root','');

$db = 

//$res = mysql_query("SELECT * FROM songs ORDER BY title") or die ("Invalid query: " . mysql_query());  

//$res = mysql_query ("SELECT * FROM mytable ORDER BY name") or die ("Invalid query: " . mysql_query());  

$res = mysql_query ("SELECT * FROM mytable") or die ("Invalid query: " . mysql_query());  

echo '<label>Select value: </label>'; 
echo '<select id="email" name="email">';  
echo '<option value="">Select Email</option>';  

while ($row = mysql_fetch_assoc($res)) 
//     $va = $row['title']; 
     $va = $row['email'];     
	echo "<option value='$va'>$va</option>";  
  echo '</select>';


Edited by Ezzaral: Added code tags. Please use them to format any code that you post.

6 Years
Discussion Span
Last Post by diafol
//=======after connected to db =======================
$icount = 0;
$query = "SELECT * FROM something "; 
 $result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_BOTH)){
$name[$icount] = $row['name'];
$email[$icount] = $row['email'];


echo "<select size='1'>";
for ( $counter = 1 ; $counter <= $icount; $counter += 1) {

echo "<option value='$email[$counter]'>$name[$counter]</option>"; 
echo "</select>";

Edited by HITMANOF44th: n/a


You're using two loops instead of one. I don't know how that's an improvement.

Are you trying to post a solution? Have you got a problem that needs solving? Either way, please put your code in appropriate tags.


//do connection
$r = mysql_query ("SELECT * FROM mytable") or die ("Invalid query: " . mysql_query()); 
$op = '<label>Select value: </label>\n<select id="email" name="email">\n\t<option value="">Select Email</option>'; 
if(mysql_num_rows($r) > 0){
  while($d = mysql_fetch_array($r)){
    $f = stripslashes($d['title']);
    $op .= "\n\t<option value=\"$f\">$f</option>";
$op .= '\n</select>';

i like your way better the other is just easier to understand but correct me if im wrong but in your code you still need to echo the $op for it to be seen


No you're quite right Hitman. You still need an echo. I place this code in an include file or in a function or above the DTD in a standalone page. I can these just echo $op wherever I need it in the page. This way I keep the bulk of the code separate from the logic (HTML)*. I should say, that this is how I do it - perhaps it's not necessarily the best way.

*OK, I've included HTML in the output string, so I've just contradicted myself. But on balance, I still think it's easier that way.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.