douyi7283 2018-07-12 23:40
浏览 29

使用PHP通过变量选择日期之间的行

I'm trying to fetch all rows where the date column's value is a day in july using the code below:

$july="07";
$query=$conn->prepare("SELECT * FROM table WHERE date BETWEEN '2018-?-01' AND '2018-?-31'");
$query->execute($july,$july);
$row=$query->setFetchMode();

I have also tried like this:

$july="07";
$month_1="'2018-".$july."-01'";
$month_2="'2018-".$july."-31'";

$query=$conn->prepare("SELECT * FROM table WHERE date BETWEEN ? AND ?");
$query->execute(array($month_1,$month_2));
$row=$query->setFetchMode();

1st case, I get the following error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in file.php on line 35

I assume I get that error because I cannot have '?' in a query between single brackets.

Second case, I get nothing at all.

Solved it with this:

SELECT * FROM table WHERE YEAR(date)=2018 AND MONTH(date)=?
  • 写回答

2条回答 默认 最新

  • doujia3441 2018-07-12 23:54
    关注

    First case error is because you passed two variables to PDO::execute() and its expecting array there.

    Suggested Reading...

    http://php.net/manual/en/pdostatement.execute.php

    Second case .. ummm.. you sure it does nothing?

    Select * from mytable where date <= '2018-07-31' and date >= '2018-07-01'  
    

    or whatever... this maybe ...

    select * from mytable where date between UNIX_TIMESTAMP(STR_TO_DATE('Jul 01 2018 12:00AM', '%M %d %Y %h:%i%p')) and UNIX_TIMESTAMP(STR_TO_DATE('Jul 31 2018 11:59PM', '%M %d %Y %h:%i%p'))
    

    Never use * to return all columns in a table–it’s lazy. You should only extract the data you need. Even if you require every field, your tables will inevitably change. -https://www.sitepoint.com/mysql-mistakes-php-developers/

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP