Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate a Drop down box from a mySQL table in PHP

Tags:

php

mysql

I am trying to populate a Drop down box from results of a mySQL Query, in Php. I've looked up examples online and I've tried them on my webpage, but for some reason they just don't populate my drop down box at all. I've tried to debug the code, but on the websites I looked at it wasn't really explained, and I couldn't figure out what each line of code. Any help would be great :)

Here's my Query: Select PcID from PC;

like image 617
Donnie Avatar asked Mar 04 '11 04:03

Donnie


People also ask

How get value from dropdown in database in PHP?

php $sql = "select * from mine where username = '$user' "; $res = mysql_query($sql); while($list = mysql_fetch_assoc($res)){ $category = $list['category']; $username = $list['username']; $options = $list['options']; ?>

How do I populate a dropdown list with array values in PHP?

Answer: Using foreach loop We can populate the dropdown list with array values in PHP using the foreach loop. Here, populating the dropdown list means adding items to the list. In HTML, we add items to the dropdown list using the <option> tag, but in PHP, we can add items to the dropdown list using dynamically.


2 Answers

You will need to make sure that if you're using a test environment like WAMP set your username as root. Here is an example which connects to a MySQL database, issues your query, and outputs <option> tags for a <select> box from each row in the table.

<?php

mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT PcID FROM PC";
$result = mysql_query($sql);

echo "<select name='PcID'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['PcID'] . "'>" . $row['PcID'] . "</option>";
}
echo "</select>";

?>
like image 179
Dan Grossman Avatar answered Oct 23 '22 14:10

Dan Grossman


Below is the code for drop down using MySql and PHP:

<?
$sql="Select PcID from PC"
$q=mysql_query($sql)
echo "<select name=\"pcid\">"; 
echo "<option size =30 ></option>";
while($row = mysql_fetch_array($q)) 
{        
echo "<option value='".$row['PcID']."'>".$row['PcID']."</option>"; 
}
echo "</select>";
?>
like image 44
sush Avatar answered Oct 23 '22 13:10

sush