【发布时间】:2014-08-14 17:45:12
【问题描述】:
我有这个代码
<?php
include 'dbconnect.php'; ?>
<head>
</head>
<body>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]?>">
<input type="text" name="product_name"/>
<input type="text" name="product_price" />
<select name="product_cat">
<?php
$results = $connect->query("SELECT * FROM categories ORDER BY cat_name");
while($row = $results->fetch_array()) {
extract($row);
echo "<option value='"."{$cat_name}"."'>"."{$cat_name}"."</option>";
}
$results->free();
?>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if($_POST){
$sql = "INSERT INTO products (prd_name, prd_price, cat_id) VALUES(?,?,?)";
if($stmt = $connect->prepare($sql) )
{
$productname = $_POST['product_name'];
$productprice = $_POST['product_price'];
$productcat = $_POST['product_cat'];
$stmt->bind_param("sii", $productname, $productprice, $productcat);
if($stmt->execute())
{
echo "Created";
$stmt->close();
}else{
die("Unable to create category.");
}
}else{
die("Unable to prepare statement.");
}
$connect->close();
}
?>
</body>
</html>
这里的类别名称是从一个名为 categories 的表中调用的。您可以在下拉菜单中看到代码。一旦用户选择类别名称,填写产品名称和产品价格,表格就会将所有三个数据保存到一个名为 products 的表中。
还有一个名为 category_product 的第三个表,其中包含两列 prd_id 和 cat_id(产品 id 和类别 id)。我需要将产品的 ID 和类别与此表格一起记录到此表中。
简而言之,当只有名称被回显时,我如何从类别表中获取类别 id,以及如何知道最后保存的产品 id,然后将两条记录插入到第二个(category_products)表中同一时间。
【问题讨论】:
-
首先,我会使用 所以你有你catId。然后对于最后一个插入 id,使用 mysqli_insert_id 将返回最后一个查询插入的 id
-
@Psychokiller1888 好的。我会尝试然后回复你。感谢您的建议。