在使用php创建的表单中创建一个下拉菜单

时间:2015-03-12 15:52:17

标签: php html mysql

我有一个用php创建的表单来编辑MySQL数据库中的记录。我想为这个表格添加一个下拉菜单,用于"类型"字段,但我不知道如何创建它而不会丢失数据库字段中已有的数据。

<?php
require_once '../php/dbconfig.php';
// Create connection
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

if (isset($_POST['update'])) {
  $UpdateQuery = "UPDATE members SET name='$_POST[name]', type='$_POST[type]', physicaladdress='$_POST[physicaladdress]', billingaddress='$_POST[billingaddress]', contact='$_POST[contact]', phone='$_POST[phone]', fax='$_POST[fax]', email='$_POST[email]', web='$_POST[web]', description='$_POST[description]' WHERE id='$_POST[id]'";
  mysqli_query($conn, $UpdateQuery);
}

$result = mysqli_query($conn, "SELECT * FROM members ORDER BY name");
echo "<br />";
echo "<table border=0>
<tr>
<th>Name</th>
<th>Type</th>
<th>Physical Address</th>
<th>Billing Address</th>
<th>Contact Name</th>
<th>Phone</th>
<th>Fax</th>
<th>Email</th>
<th>Web</th>
<th>Description</th>
</tr>" ;

while($record = mysqli_fetch_array($result)) {
  echo "<form action = admin-update.php method = post>";
  echo "<tr>";
  echo "<td>" . "<input type=text size=42 name=name value='" . $record['name'] . "' </td>";
  echo "<td>" . "<input type=text size=30 name=type value='" . $record['type'] . "' </td>"; 
  echo "<td>" . "<input type=text size=60 name=physicaladdress value='" . $record['physicaladdress'] . "' </td>";
  echo "<td>" . "<input type=text size=60 name=billingaddress value='" . $record['billingaddress'] . "' </td>";
  echo "<td>" . "<input type=text size=20 name=contact value='" . $record['contact'] . "' </td>";
  echo "<td>" . "<input type=text size=10 name=phone value='" . $record['phone'] . "' </td>";
  echo "<td>" . "<input type=text size=10 name=fax value='" . $record['fax'] . "' </td>";
  echo "<td>" . "<input type=text size=25 name=email value='" . $record['email'] . "' </td>"; 
  echo "<td>" . "<input type=text size=25 name=web value='" . $record['web'] . "' </td>"; 
  echo "<td>" . "<input type=text 50 name=description value='" . $record['description'] . "' </td>"; 
  echo "<td>" . "<input type=hidden name=id value='" . $record['id'] . "' </td>";
  echo "<td>" . "<input type=submit name= update value=Update" . " </td>";
  echo "</form>";
}
echo "</table>";

$conn->close();
?>

非常感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

您应该能够使用选项将输入中的类型更改为选择,并将数据库中的值包含在其中一个选项中。

我建议:

$selectType = '<select name="type">';
$selectType .= '<option value="'. $record['type'] .'">"'. $record['type'] .'"</option>';
$selectType .= '<option value="Opt1">Option1</option>';
$selectType .= '<option value="Opt2">Option2</option>';
$selectType .= '<option value="Opt3">Option3</option>';
$selectType .= '</select>;

然后,在你的while循环中:

echo "<td>" . $selectType . "</td>";  

我希望这适合你。如果没有,或者它没有回答你的问题,请告诉我。