Php 从下拉列表中选择要插入的外部表名,并插入到其他仅具有id的表中

Php 从下拉列表中选择要插入的外部表名,并插入到其他仅具有id的表中,php,sql,Php,Sql,我已经做了一些数据库规范化,并为product表创建了一个外部producttype表,因为它的值是固定的。现在我遇到了一些php表单问题 我正在努力工作:添加一个产品并创建一个producttype选项(下拉列表中的producttypes),并且只将producttypeid存储到产品记录中 我的桌子: 产品(产品名称,产品类型) 产品类型(产品类型ID,产品类型 感谢您的支持!我仍然无法使下拉项在表单中工作,并且当仅提供并提交productname时,我会收到消息“1 record ad

我已经做了一些数据库规范化,并为product表创建了一个外部producttype表,因为它的值是固定的。现在我遇到了一些php表单问题

我正在努力工作:添加一个产品并创建一个producttype选项(下拉列表中的producttypes),并且只将producttypeid存储到产品记录中

我的桌子:

产品(产品名称,产品类型)

产品类型(产品类型ID,产品类型

  • 感谢您的支持!我仍然无法使下拉项在表单中工作,并且当仅提供并提交productname时,我会收到消息“1 record addedError:No database selected”。这将生成producttype为空的新记录
producttype表数据库中有两条记录应该显示在下拉列表中

<?php
// connection with database
include('connect.php');

// check page request
if (isset($_POST["submit"])){

// query insert to product
$sql="INSERT INTO product (productname, producttype)
VALUES('$_POST[productname]','$_POST[producttype]')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";

// query select from producttype
$query="SELECT producttypeid, producttype FROM producttype";
$result = mysql_query($query) or die ("Error: " . mysql_error());

// store options in array
$product_types = array();
while (list($id, $name,) = mysql_fetch_row($result))
{
$product_types[$id] = $name;
}
// safety against cross-site scripting 
function h($str)
{
return htmlentities($str, ENT_QUOTES, "UTF-8");
}
}?>

<!-- html input form !-->
<html>
<body>
<form action="addproduct.php" method="post">
<input type="hidden" name="submit" value="1">
Productname: <input type="text" name="productname"></br>
Producttype: <select>
<?php foreach($product_types as $id => $label): ?>
<option value="<?php echo h($id); ?>"><?php echo h($label); ?></option>
<?php endforeach; ?>
</select></br>
<input type="submit">
</form>
</body>
</html>
您的
中只有一个
标记。要在选择菜单中显示所有产品类型,您需要将选项存储在一个数组中:

$product_types = array();
while (list($id, $name,) = mysql_fetch_row($result))
{
    $product_types[$id] = $name;
}
然后显示选项:

<select>
    <?php foreach($product_types as $id => $label): ?>
        <option value="<?php echo h($id); ?>"><?php echo h($label); ?></option>
    <?php endforeach; ?>
</select>
function h($str)
{
    return htmlentities($str, ENT_QUOTES, "UTF-8");
}