首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >选择要下拉列表的外部表名称,然后只使用id插入到其他表中。

问选择要下拉列表的外部表名称,然后只使用id插入到其他表中。
EN

Stack Overflow用户
提问于 2013-11-04 15:55:39
回答 1查看 139关注 0票数 0

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

我试图使工作:添加一个产品,并做出一个producttype选项(产品类型从下拉列表),并只存储产品的产品记录。

我的桌子:

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

producttype (producttypeid,producttype)

  • 谢谢你支持我!但是,我仍然无法获得在表单中工作的下拉项,当只给出产品名称并提交时,我会得到消息"1 record addedError: No database selected“--这将生成一个producttype空白的新记录。

产品类型表数据库中有两条记录应该显示在下拉列表中。我的更新代码如下

代码语言:javascript
复制
<?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>
EN

回答 1

Stack Overflow用户

发布于 2013-11-04 16:04:00

在您的<option>中只有一个<select>标记。要在“选择”菜单中显示所有产品类型,需要将这些选项存储在数组中:

代码语言:javascript
复制
$product_types = array();
while (list($id, $name,) = mysql_fetch_row($result))
{
    $product_types[$id] = $name;
}

然后显示以下选项:

代码语言:javascript
复制
<select>
    <?php foreach($product_types as $id => $label): ?>
        <option value="<?php echo h($id); ?>"><?php echo h($label); ?></option>
    <?php endforeach; ?>
</select>

h函数用于转义输出,这样您的代码就不会受到跨站点脚本的攻击

代码语言:javascript
复制
function h($str)
{
    return htmlentities($str, ENT_QUOTES, "UTF-8");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19771673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档