Page 1 of 1

populate select options from mysql db

Posted: Fri Feb 24, 2012 1:32 pm
by inosent1
i have a table named data with 5 records.

in a column named 'product' i have 5 entries:

door
table
seat
carpet
window

i have a field in an html form named 'products'. it is a "select" field, and i want to read from the data table all the entries in the product column to a user looking at the from can select one of the products.

if there is a way to use php code for this that would be really helpful

tia

Re: populate select options from mysql db

Posted: Fri Feb 24, 2012 1:44 pm
by mikosiko
sure it is a way... matter of fact if you search for today post you will find one with code to do that ("Form not passing field value")... just need to be adjusted/optimized for your particular situation

Re: populate select options from mysql db

Posted: Fri Feb 24, 2012 2:28 pm
by inosent1
here is what i have extrapolated from that post:

Code: Select all

<span class="style4"><select name="company">
<!-- insert -->
<?php
include("dbinfo.inc.php");
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

$query="SELECT DISTINCT company FROM users;
$result = mysql_query($query) ;

while($nt=mysql_fetch_array($result))
{
echo "<option value=\"$nt[company]\">$nt[company]</option>";
}
mysql_close($connection);
     ?>
         </select>

i dont think the query is right. in the query not sure where to place the table name and column name to draw out the records. there is a lot of extraneous code in your example. i am trying to simplify things to pull the data as efficiently as possible.

thanks for the reply

Re: populate select options from mysql db

Posted: Fri Feb 24, 2012 2:44 pm
by mikosiko
good... you are in the right track

Code: Select all

include("dbinfo.inc.php");   /// probably you don't need this line (in case that you just copied it from the example)

mysql_connect(localhost,$username,$password);  // obviously you must define $username and $password for your DB

@mysql_select_db($database) or die( "Unable to select database");  // and also you must define which $database you will connect... and take out of here the error suppression character (@)

$query="SELECT DISTINCT company FROM users";   /// modify here... SELECT <your fieldnames> FROM <your table>

$result = mysql_query($query) ;  // this need to be modified to trap errors  ... temporarily you can add OR die("SQl Error : " . mysql_error()) before the ; (like the line mysql_select_db before)

while($nt=mysql_fetch_array($result))   // Better to use mysql_fetch_assoc  here
{
echo "<option value=\"$nt[company]\">$nt[company]</option>"; // and here you use the field from your table

Re: populate select options from mysql db

Posted: Fri Feb 24, 2012 8:13 pm
by inosent1
got it, thanks, works perfectly