user3138025 user3138025 - 1 month ago 8
PHP Question

How to get HTML SELECT populated from Database

I'm trying to get an HTML SELECT field within a form to be populated from a database column. I can read the column fine, and can use fprint or echo to see the results. The problem is, I can't seem to get the array based on the column to appear as selections in the SELECT field. I'm able to produce a field with a pull-down selector, but the values aren't populated. How to I get the values from the Array into an HTML SELECT / OPTION field?
Here's a subset of the code I'm using:

<?php
$link = new mysqli("localhost","USER","PASSWORD", "DATABASE");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!$link->set_charset("utf8"))
{
printf("Error loading character set utf8: %s\n", $link->error);
exit();
}

$role_sql = "SELECT role FROM lu_role";
$role_result = mysqli_query($link, $role_sql);
$options = "";
while($row1 = mysqli_fetch_array($role_result))
{
$options = $options."<option>$row1[1]</option>";
}

//Using the following to validate that I can get the query results in an array.
while ($row = $role_result->fetch_assoc())
{
printf($row["role"]);
}
?>
<form action="post.php" method="post">
<table class="table_600_reg">
<tr>
<td width="120">Father</td>
<td width="200" align="left">
<select>
<?php echo $options;?>
</select>

Answer

You are missing value="" here $options = $options."<option value=''>$row1[1]</option>";

Comments