1

我试图创建一个简单的 SQL INSERT 否则 UPDATE 语句,但老实说我不知道​​我在做什么

到目前为止,这是我的功能

function addInventoryBook($isbn, $sku, $price, $quantity, $condition, $dateOpened){
   $q = "INSERT INTO ".TBL_INVENTORY." VALUES('$isbn', '$sku', $price, 
   $quantity, '$condition', $dateOpened)
   ON DUPLICATE KEY UPDATE VALUES('$isbn', '$sku', $price, $quantity, 
   '$condition', $dateOpened)";     

   return mysql_query($q, $this->connection);           
}

似乎更新价格字段的先前功能正在工作

function addInventoryBook($isbn, $sku, $price, $quantity, $condition, $dateOpened){
   $q = "INSERT INTO ".TBL_INVENTORY." VALUES('$isbn', '$sku', $price, 
   $quantity, '$condition', $dateOpened)
   ON DUPLICATE KEY UPDATE price = $price";     

   return mysql_query($q, $this->connection);           
}
4

2 回答 2

5

我会这样写,而不是第二次提供每个值:

ON DUPLICATE KEY UPDATE 
  isbn       = VALUES(isbn)
  sku        = VALUES(sku)
  price      = VALUES(price)
  quantity   = VALUES(quantity)
  condition  = VALUES(condition)
  dateOpened = VALUES(dateOpened)

(如果插入成功,这将分配将被插入的值。)

(您可能不希望将值分配给构成插入违反的“唯一”键的任何列;我在这里包含了所有列,因为这就是您在尝试中显示的内容。)

于 2012-07-24T18:16:34.683 回答
2

Assuimg TBL_INVENTORY 是具有列值的字符串:

$q = "INSERT INTO ".TBL_INVENTORY." VALUES('$isbn', '$sku', $price,     $quantity, '$condition', $dateOpened) ON DUPLICATE KEY UPDATE isbn='$isbn', sku='$sku', price='$price', quantity='$quantity', condition='$condition', dateOpened='$dateOpened'";

参考链接:http ://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

于 2012-07-24T18:14:37.460 回答