在MySQL中更新包含外键列的表

时间:2011-04-05 12:57:14

标签: php mysql foreign-keys sql-update

我正在处理与外键关联的3个表,并设置为ON UPDATE CASCADEON DELETE CASCADE。这些表格为categorysubcategoryproducts

products表 - PID(PK),productname,subcatid(FK)

subcategory table - subcatid(PK),subcategoryname,catid(FK)

category表 - catid(PK),categoryname

当我想更改产品名称时,UPDATE产品表的正确查询是什么?另外,如果我想使用表单更改产品的子类别?

我正在使用一个表格,该表格成功地预先填写了字段 - 产品名称,子类别名称,但它不更新产品表中的记录,意味着它什么都不做,并且不会更改产品名称和子类别名称。

感谢任何帮助。

正在使用以下代码

<?php 
// Parse the form data and add inventory item to the system
if (isset($_POST['PRODUCT_NAME'])) {
    $pid = mysql_real_escape_string($_POST['thisPID']);
    $catalog_no = mysql_real_escape_string($_POST['CATALOG_NO']);
    $product_name = mysql_real_escape_string($_POST['PRODUCT_NAME']);
    $price = mysql_real_escape_string($_POST['PRICE']);
    $composition = mysql_real_escape_string($_POST['COMPOSITION']);
    $size = mysql_real_escape_string($_POST['SIZE']);
    $subcat = mysql_real_escape_string($_POST['SUBCAT_ID']);
    // See if that product name is an identical match to another product in the system
    $sql = mysql_query("UPDATE products SET CATALOG_N0='$catalog_no', PRODUCT_NAME='$product_name', PRICE='$price', COMPOSITION='$composition', SIZE='$size', SUBCAT_ID='$subcat' WHERE PID='$pid'");
    header("location: inventory_list.php"); 
    exit();
}
?>

<?php 
// Gather this product's full information for inserting automatically into the edit form below on page
if (isset($_GET['pid'])) {
    $targetID = $_GET['pid'];
    $sql = mysql_query("SELECT products.PID, products.CATALOG_NO, products.PRODUCT_NAME, products.PRICE, products.COMPOSITION, products.SIZE, products.SUBCAT_ID, subcategory.SUBCAT_ID, subcategory.SUBCATEGORY_NAME FROM (products, subcategory) WHERE subcategory.SUBCAT_ID=products.SUBCAT_ID AND PID='$targetID' LIMIT 1");
    $productCount = mysql_num_rows($sql); // count the output amount
    if ($productCount > 0) {
        while($row = mysql_fetch_array($sql)){ 

             $catalog_no = $row["CATALOG_NO"];
             $product_name = $row["PRODUCT_NAME"];
             $price = $row["PRICE"];
             $composition = $row["COMPOSITION"];
             $size = $row["SIZE"];
             $subcat = $row["SUBCAT_ID"];
        }
    } else {
        echo "You dont have that product";
        exit();
    }
}
?>

1 个答案:

答案 0 :(得分:3)

您没有将产品名称用作外键,因此是一个简单的标准

UPDATE products SET productname='New Name of Product' where PID=XXX;

会做到这一点。同样适用于产品中的subcatid。只要子子类表中存在新的子域ID,您就可以通过简单的

将products.subcatid更改为您想要的任何内容。
UPDATE products SET subcatid=New_ID where PID=XXX;