Monday 9 November 2009

Adding items to a dropdown from a MYSQL Database

*** Disclaimer I do not know if this is the best method or is even correct, if you are the type of person who reads things on the internet, tries them out and then gets annoyed when things don't work out. Then maybe this post is not for you, go outside instead and enjoy some fresh air ***

My next php project is, I'm building a small recipe section for my chance1234.com site. I've started on working on a form to allow myself to add recipes to the database.

One of the options I want when adding recipes is to be able to clarify recipes by type. ie pasta dishes, soups etc

What I did was set up a table on mysql database called rtype


CREATE TABLE IF NOT EXISTS `rType` (
`rId` int(11) NOT NULL auto_increment,
`type` varchar(255) NOT NULL,
`Notes` varchar(255) NOT NULL,
PRIMARY KEY (`rId`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

Then on my php file, I created the following function

Function listRecipesTypes()
{
$html ='<select name="'.$name.'">';
$sql="SELECT rID,type FROM rType";

$result = mysql_query($sql)
or die(mysql_error());

if (mysql_num_rows($result) == 0)
{
echo "<em>No created.</em>";
}
else
{
while ($row = mysql_fetch_array($result))
{
$html .= '<option value='. $row['rId'].'>'.$row['type'].'</option>';
}
}
$html .= '</select>';
echo $html;
}

?>


I adapted the code from a Make a Website post. Ideally what I want to do is adapt the function so I can chuck any array at it.

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails