Error matching dates in PDO

这一生的挚爱 提交于 2019-12-24 11:29:38

问题


I am trying to update records on a database table where the date column matches the present year and month. I keep getting this error

Incorrect datetime value: '%2018-06%' for column 'created_at'

This is what I am doing

$current_month = date("Y-m");
$points = 4;
$freelancer_id =4;
$update = "UPDATE monthly_limits SET points = :points WHERE freelancer_id = :freelancer_id AND 
created_at LIKE concat('%', :current_month, '%')";
$query = $this->db->prepare($update);
$query->bindParam("points", $points);
$query->bindParam("current_month", $current_month);
$query->bindParam("freelancer_id", $freelancer_id);
$query->execute();

Please how do I resolve this?


回答1:


This is not how dates work in a SQL database. A like statement is meant to be used with string types, whereas dates are a glorified number. Given the style of parameters, I'm betting your best bet is to do two difference checks. One on month and one on year.

You haven't specified your RDBMS, so I'll give a MySQL answer.

UPDATE 
  monthly_limits SET points = :points 
WHERE 
  freelancer_id         = :freelancer_id 
  AND Year(created_at)  = :current_year
  AND Month(created_at) = :current_month



回答2:


You cannot use wildcards with dates and the db value as a date.

You would be much better off getting the date pieces you want to compare and use those directly:

$current_year = date("Y"); 
$current_month = date("mm");
$points = 4;
$freelancer_id =4;
//Use the SQL version you have to get the date parts this is general.
$update = "UPDATE monthly_limits SET points = :points WHERE freelancer_id = :freelancer_id AND 
        MONTH(created_at) = :current_month AND YEAR(created_at) = :current_year";
        $query = $this->db->prepare($update);
        $query->bindParam("points", $points);
        //Separated these
        $query->bindParam("current_month", $current_month);
        $query->bindParam("current_month", $current_year);
        $query->bindParam("freelancer_id", $freelancer_id);
        $query->execute();



回答3:


In order to take advantage of indexes, I would instead suggest you use full dates. Just set one date to the beginning of the month, and the other date to the end of the month and search for dates in that range:

$date_start = date('Y-m-1 00:00:00');
$date_end = date('Y-m-t 23:59:59');

$points = 4;
$freelancer_id =4;
$query = $this->db->prepare("UPDATE monthly_limits 
    SET points = :points 
    WHERE freelancer_id = :freelancer_id 
    AND created_at >= :date_start
    AND created_at <= :date_end"
);
$query->bindParam("points", $points);
$query->bindParam("date_start", $date_start);
$query->bindParam("date_end", $date_end);
$query->bindParam("freelancer_id", $freelancer_id);
$query->execute();


来源:https://stackoverflow.com/questions/51047874/error-matching-dates-in-pdo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!