Jump to content

PHP Code to populate listbox with values from database


jlgray48

Recommended Posts

I'm trying to create a php script that creates a listbox and populates the list with values from a table named Inventorytable. I only need the values from the ItemName field to be populated in the listbox.

 

Here is what I have so far.......

 

<?

 

$conn=mysql_connect("127.0.0.1", "odbc", "") ;

mysql_select_db("php012",$conn) or die ("error cannot connect");

$sql = "select itemname from inventorytable;";

$result = mysql_query($sql,$conn);

while ($array = mysql_fetch_array($result)) {

print $array[itemName];}

<html>

<SELECT >

<OPTION VALUE="01">Option 1

<OPTION VALUE="02">Option 2

<OPTION VALUE="03">Option 3

</SELECT>

</html

?>

 

 

<


<?

$conn=mysql_connect("127.0.0.1", "odbc", "") ;
mysql_select_db("php012",$conn) or die ("error cannot connect");
$sql = "select itemname from inventorytable";
$result = mysql_query($sql,$conn);
?>
<select name="item">
<?
while ($array = mysql_fetch_array($result)) {
?>
<OPTION VALUE="<?=$array['itemname'];?>"><?=$array['itemname'];?></option>
<? } ?>
</SELECT>
</html>
?>

Okay, im assuming you have an ID field for each item in the inventory table called itemid.  Change the field name as necessary.

 

I have also added "or die(mysql_error());" after your query for debugging purposes.

 


<select name="items>	
<?
$conn=mysql_connect("127.0.0.1", "odbc", "") ;
mysql_select_db("php012",$conn) or die ("error cannot connect");

$sql = "SELECT itemid, itemname FROM inventorytable;";
$result = mysql_query($sql,$conn) or die(mysql_error());
while ($array = mysql_fetch_array($result)) {
	$itemId = $array['itemname'];
	$itemName = $array['itemname']; ?>
	<option value="<?=$itemId?>"><?=$itemName?>
<?	}		

?>
</select>	

In that case, just this

 

<select name="items">
<?
$conn=mysql_connect("127.0.0.1", "odbc", "") ;
mysql_select_db("php012",$conn) or die ("error cannot connect");

$sql = "SELECT * FROM inventorytable";
$result = mysql_query($sql,$conn) or die(mysql_error());
while ($array = mysql_fetch_array($result)) {
$itemName = $array['itemname']; ?>
<option value="<?=itemName?>"><?=$itemName?>
<?
}  ?>
</select>

It may be that short tags arent enabled on your server

 

Try replacing the opening tags

 

<?

 

with

 

<?php

 

Leave the closing tags ?> as they are

 

putting something like

 

<?=$myVar?>

 

is a shortcut way of putting

 

<?php echo "$myVar"; ?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.