Assuming we have the browsers
table in the database:
id | name
---+------------------
1 + Google Chrome
---+------------------
2 + Firefox
---+------------------
3 + Opera
---+------------------
4 + Safari
---+------------------
5 + Internet Explorer
---+------------------
We can generate the following HTML with PHP:
<?php
//...
$result = mysqli_query($mysqli, "SELECT 'id', 'name' FROM 'browsers'");
echo "<select name='browser'>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='{$row['id']}' label='{$row['name']}'>{$row['name']}</option>";
}
echo "</select>";
The HTML output will be:
<select name='browser'>
<option value='1' label='Google Chrome'>Google Chrome</option>
<option value='2' label='Firefox'>Firefox</option>
<option value='3' label='Opera'>Opera</option>
<option value='4' label='Safari'>Safari</option>
<option value='5' label='Internet Explorer'>Internet Explorer</option>
</select>
When the form is submitted, in PHP you can retrieve the value of the value
attribute selected. This value is the id
of the selected registry of the browsers
table, so to get the name of the selected browser, just select the respective database record:
<?php
// ...
if ($stmt = mysqli_prepare($mysqli, "SELECT 'id', 'name' FROM 'browsers' WHERE 'id' = ?")) {
mysqli_stmt_bind_param($stmt, "i", $_POST["browser"]);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $name);
mysqli_stmt_fetch($stmt);
echo "O navegador selecionado foi: ", $name;
}
The complete code tested was:
<form action="" method="post">
<select name="browser">
<?php
$mysqli = mysqli_connect("localhost", "root", "", "sopt");
$result = mysqli_query($mysqli, "SELECT 'id', 'name' FROM 'browsers'");
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='{$row['id']}' label='{$row['name']}'>{$row['name']}</option>";
}
?>
</select>
<button>Enviar</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($stmt = mysqli_prepare($mysqli, "SELECT 'id', 'name' FROM 'browsers' WHERE 'id' = ?")) {
mysqli_stmt_bind_param($stmt, "i", $_POST["browser"]);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $name);
mysqli_stmt_fetch($stmt);
echo "O navegador selecionado foi: ", $name;
}
}
?>