【问题标题】:Saving data into two tables at the same time同时将数据保存到两个表中
【发布时间】: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 好的。我会尝试然后回复你。感谢您的建议。

标签: php mysql


【解决方案1】:

您可以从第一个语句中获取insert_id 以在第二个语句中使用。这里有一些伪代码可以帮助你解决这个问题

if($stmt->execute()) {
     $record_id = $stmt->insert_id;
     $sql = "INSERT table2(data, table1_id) VALUES($someval, $record_id)";
     // Run the query here
}

【讨论】:

  • 谢谢先生,但是如何获取类别名称的 id?。
  • 按照我在上面的评论中所写的方式传递它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多