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

<?php  


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

$db = 
mysql_select_db('mydb');



//$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>';

?>

Recommended Answers

All 4 Replies

//=======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)){
$icount++;
$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>";
Member Avatar for diafol

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

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

2p:

//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

Member Avatar for diafol

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.