SpeedBurner
SpeedBurner

Reputation: 731

Use HTML dropdownlist made in PHP with data from MySQL database

I have a PHP script which connects to a MySQL database and creates an HTML dropdown list with data retrieved from it. The script works, I just don't understand how I'm supposed to use it in an HTML form.

The PHP script, named CountryList.php, looks like this:

<?php
function createCountryList() {
    $con = mysql_connect("localhost","user","pass");
    mysql_select_db('database', $con);

    $sql="SELECT Country FROM CountryList";
    $result = mysql_query($sql,$con);

    echo "<select name=country value=''>Country</option>";
    echo "<option value=0>Select Country</option>";
    echo "<option value=1></option>";

    $curvalue=2;
    while($nt=mysql_fetch_array($result)){
        echo "<option value=$curvalue>$nt[Country]</option>";
        $curvalue = $curvalue+1;
    }
    echo "</select>"; 
    mysql_close($con);
}
?>

I tried including the PHP file in the head of the HTML page with:

<?php include("CountryList.php"); ?>

And then I tried calling the function which creates the dropdown menu in a form later on:

<form action="insert.php" method="POST">
<label>Which country are you from?</label>
<?php createCountryList(); ?>
</form>

Since nothing happens, I did it wrong. Any advice? Help is appreciated.

EDIT: Bah, I knew it was something silly. The page was an HTML file, PHP didn't process it. Changing the HTML file to PHP solved everything.

Upvotes: 0

Views: 4955

Answers (4)

StBlade
StBlade

Reputation: 285

This is what I did in one of my HTML forms. Try and see if it works for you.

<select name="country"><?php createCountryList();?></select>

What you do here is on the page where you want the selectbox, you put in this code and call the function.

Upvotes: 0

Jaime
Jaime

Reputation: 1410

Try changing echo "<option value=$curvalue>$nt[Country]</option>"; to echo "<option value=$curvalue>{$nt['Country']}</option>";

Echoing out arrays requires curly brackets around the array index if inside a string. Also the index needs quotes or php will assume constant.

Upvotes: 0

Adithya Surampudi
Adithya Surampudi

Reputation: 4454

Are you sure its in the same folder. Its a good practice to do a check before

if ((include 'CountryList.php') == 'OK') {
createCountryList();
}
else{
echo "Didnt import";
}

Dont do brackets like include()

Upvotes: 0

canadiancreed
canadiancreed

Reputation: 1984

What happens when you change this line

echo "<select name=country value=''>Country</option>";

to this

echo "<select name='country'>Country";

Upvotes: 1

Related Questions