CrawlerWebSolutions
CrawlerWebSolutions

Reputation: 35

How do I automatically populate the options of a select element in HTML using PHP and MySQL?

First and foremost first time posting a question be easy on me please :)

I am trying to generate a `Form DropDownList (Select/options) using PHP/MySQL. I need the options to automatically populate using tablenames from my database that only contain ".com"

This is my current code:

<?php
$con = mysql_connect("localhost","username","password");
$db = mysql_select_db("dbname",$con);
$result = mysql_query("SHOW TABLES LIKE '%.com%'",$con) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {
$table = $tableName[0];
}
;
$option .= '<option value = "website-manager.php?table='.$table.'">'.$table.'</option>';
?>
<form name="form" id="form">
  <select name="jumpMenu" id="jumpMenu">
    <option value="#">Select Website</option>
    <?php echo $option ; ?>
  </select>
  <input type="button" name="go_button" id= "go_button" value="Go" onclick="MM_jumpMenuGo('jumpMenu','parent',0)" />
</form>

When I use this code, only one tablename populates as opposed to the 15 currently in my database.

How can I correct my code above to populate all of the tablenames?

Upvotes: 1

Views: 319

Answers (2)

Vladimir Vukanac
Vladimir Vukanac

Reputation: 984

As suggested move } of while end below - Try replacing part with this:

<?php
$filter = '%wp_%';
$con = mysql_connect("localhost","root","pwd");
$db = mysql_select_db("enterDbName",$con);
$result = mysql_query("SHOW TABLES LIKE '".$filter."'",$con) or die('cannot show tables');
$option = '';
while($tableName = mysql_fetch_row($result)) {
    $table = $tableName[0];
    $option .= '<option value = "website-manager.php?table='.$table.'">'.$table.'</option>';
}
?><form name="form" id="form">
    <select name="jumpMenu" id="jumpMenu">
        <option value="#">Select Website</option>
        <?php echo $option ; ?>
    </select>
    <input type="button" name="go_button" id= "go_button" value="Go" onclick="MM_jumpMenuGo('jumpMenu','parent',0)" />
</form>

Warning: This extension (mysql) is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71384

The problem is that you are overwriting $table with each iteration through the DB result set.

You need to put the data into an array like this:

$tables = array();
while ($tableName...) {
    $tables[] = $tableName[0];
}

Then output your options in a loop like this:

<option value="#">Select Website</option>
<?php
foreach($tables as $table) {
    echo '<option value="website-manager.php?table=' . urlencode($table) .'">' . $table . </option>';
}
?>

Upvotes: 2

Related Questions