【问题标题】:add a value to existing value using mysql query [duplicate]使用mysql查询将值添加到现有值[重复]
【发布时间】:2018-01-30 18:35:25
【问题描述】:

大家好,我正在研究 codeigniter。我有一张包含“数量”列的产品表。现在我需要在已经存在的数量上添加新值。

之前:

+----+-------------+  
| id | qty         |  
+----+-------------+  
|  1 | 5           |  
|  2 | 12          |  
|  3 | 50          |  
|  4 | 35          |  
+----+-------------+ 

我已经从助手尝试过这个查询(我已经在查询之前检查了 $qty$productID 的值):

$qty = 20;
$productID = 1;
$query = $ci->db->query('UPDATE products SET qty  = qty + ' . $qty . ' WHERE id = "' . $productID . '"');

在这个查询之后,它总是将值更新为 0,而不是添加到前面的示例中。 查询返回 true,但它总是将 0 添加到数据库中。这是为什么 ? 我见过许多使用相同查询的示例,但对我来说并没有发生。我该如何解决这个问题?

【问题讨论】:

  • @Bilal 你能 var_dump 查询字符串吗?当你将它复制粘贴到 mysql 客户端时会发生什么?行为是相同还是不同?
  • @Vickel 该链接解决了我的问题

标签: php mysql codeigniter


【解决方案1】:

试试这个:

private function getQty($productId)
         {
             $db = $this->db;
             $db->select('qty')->from('products')->where('id', $productId);
             $result = $db->get()->row();
             if ($result)
             {
                 return $result;
             }
             else
             {
                 return false;
             }
         }

         public function update($productId, $newQty)
         {
             $db = $this->db;
             $oldQty = $this->getQty($productId);
             $qty = $oldQty + $newQty;
             $data['qty'] = $qty;



             $db->where('id', $productId)->update('products', $data);

             if ($db->affected_rows())
             {
                 return true;
             }
             else
             {
                 return false;
             }
         }

【讨论】:

    【解决方案2】:

    这里是codeigniter方式:

    第三个参数是 FALSE,意思是不要转义文本

    $this->db->set('qty', 'qty + ' .  $qty, FALSE)
             ->where('id', $productID )
             ->update('products'); 
    

    【讨论】:

      【解决方案3】:

      尝试这样做:

      $this->db->where('id', $productID);
      $this->db->set('qty', 'qty + ' . $qty, FALSE);
      $this->db->update('products');
      

      FALSE 将给出:

      UPDATE products SET qty = qty + 5 WHERE id = '1'
      

      代替:

      UPDATE products SET qty = 'qty + 5' WHERE id = '1'
      

      更多详情here.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-16
        • 1970-01-01
        • 2012-11-01
        • 1970-01-01
        相关资源
        最近更新 更多