2011-04-05 59 views
2

我正在處理與外鍵鏈接的3個表,並且也設置爲ON UPDATE CASCADEON DELETE CASCADE。這些表格是category,subcategoryproducts更新MySQL中包含外鍵列的表

products表 - PID(PK),產品名稱,subcatid(FK)

subcategory表 - subcatid(PK),subcategoryname,CATID(FK)

category表 - CATID(PK),類別名

當我想更改產品的名稱時,對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(); 
    } 
} 
?> 
+0

什麼是你與你的表格試圖查詢?張貼它們。 – Treffynnon 2011-04-05 13:07:56

+0

使用以下代碼 – henry 2011-04-05 13:24:37

+0

使用代碼更新您的問題。評論不夠長。 – Treffynnon 2011-04-05 13:25:02

回答

3

您未使用的產品名稱爲外鍵,所以一個簡單的標準

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

會做的伎倆。產品中的小包標籤也一樣。只要在子類別表中存在的新SUBCAT ID,您可以通過再次改變products.subcatid任何你想要的,一個簡單的

UPDATE products SET subcatid=New_ID where PID=XXX; 
+0

我認爲這是我在做什麼,我正在使用更新產品SET PRODUCT_NAME ='$ product_name'WHERE PID = 1; – henry 2011-04-05 13:34:48

+1

不應該有任何問題,除非$ product_name未正確轉義。如果它有一個引號,它會「打破」查詢。總是檢查你的查詢是否成功。即使是一個基本的'$ result = mysql_query(...)或者die(mysql_error())''也會爲你節省很多時間,想知道爲什麼事情沒有成功。 – 2011-04-05 13:37:17

+0

所以要使用$ product_name我必須正確地轉義它 – henry 2011-04-05 13:44:19