从所选User_ID的最新记录开始,更新日期范围内的所有值

时间:2014-09-11 18:57:37

标签: php mysql

我需要使用值更新特殊日期及以上的所有记录。我使用波纹管查询,但它将新值添加到所有开始日期。必须仅在从所选日期到最新日期之前添加该值。谢谢大家。

datepicker    ammount
------------------------
2009-08-25    75 (+ 30)
2009-07-01    100 (+ 30)
2009-07-02    120 (+ 30) <-- Need to start adding new value (difference: 30) from here, up to the latest date.
2009-07-02    320
2009-07-02    100  

// MY UPDATE QUERY
------------------------
mysqli_query($con,"UPDATE mytable 
SET ammount = ammount + '$_POST[difference]' 
WHERE Supplier_id = '$_POST[Supplier_id]' 
AND datepicker BETWEEN '". $_POST['datepicker']."' 
AND CAST(now() AS DATE)
AND DateStamp = (select MAX(DateStamp) 
    FROM mytable  
    WHERE Supplier_id='" .$_POST['Supplier_id'] ."' 
    AND datepicker='" . $_POST['datepicker'] . "')
    ");

我可以使用以下查询选择上面的搜索,但不能更新。我做错了什么?

// THE SELECT QUERY:

$result = mysqli_query($con,"SELECT * 
FROM mytable  
WHERE Supplier_id='$_POST[Supplier_id]' 
AND datepicker = '" . $_POST['datepicker'] . "' 
AND DateStamp = (select MAX(DateStamp) 
    FROM mytable  
    WHERE Supplier_id='" .$_POST['Supplier_id'] ."' 
    AND datepicker='" . $_POST['datepicker'] . "') ");

2 个答案:

答案 0 :(得分:0)

我建议你的日期选择器可能有问题,直接将后期数据放入查询也一般都不安全,所以我建议做一些数据清理,因为这也会帮助你检查看看是什么您的查询是在提交之前进行的,如下所示:

 $difference = (int)$_POST[difference]; //Do some better sanitization here
 $supplierId = (int)$_POST[Supplier_id]; //Do some better sanitization here
 $datepicker = $_POST['datepicker']; //Do some better sanitization here

 $query = "UPDATE mytable " .
 "SET ammount = ammount + $difference  " .
 "WHERE Supplier_id = '$supplierId' " .
 "AND datepicker BETWEEN '$datepicker' AND CAST(now() AS DATE)";

 print $query;
 mysqli_query($con, $query);

这将帮助您查看您的查询是否符合您的预期。您也可以通常运行s​​elect语句而不是update语句来获取where子句,从而在表数据中选择正确的行,此时您可以将查询转换为Update查询。

答案 1 :(得分:0)

试试这个:

$from_date = date("Y-m-d", strtotime($_POST['datepicker']);

mysqli_query($con,"UPDATE mytable SET ammount = ammount + '$_POST[difference]' WHERE Supplier_id = '$_POST[Supplier_id]' AND datepicker BETWEEN '". $from_date ."' AND CAST(now() AS DATE)");

编辑:

strtotime()非常擅长将字符串转换为时间,而date()将帮助您将日期转换为mysql日期字段的正确格式。

http://php.net/manual/en/function.strtotime.php

http://php.net/manual/en/function.date.php