[英]MySQL 'Between' dates not selecting the correct results using PHP (and Codeigniter)
Here is my code (using CodeIgniter): 这是我的代码(使用CodeIgniter):
$now = date('Y-m-d');
$then = strtotime($now . '-1 week');
$then = date('Y-m-d', $then);
$q3 = $this->db->query("SELECT *
FROM posts
WHERE publish_date BETWEEN '$then' AND '$now'");
$data['posts_today'] = $q3->num_rows();
I clearly have posted at least twenty posts this week, but it only displays '1'. 我本周显然已经发布了至少20条帖子,但它仅显示“ 1”。 Any ideas why?
有什么想法吗?
Thanks! 谢谢!
Does this work for you: 这对您有用吗:
$q3 = $this->db->query("SELECT *
FROM posts
WHERE publish_date BETWEEN DATE_SUB(NOW(), INTERVAL 1 WEEK)
AND NOW()");
Potential issues I see: 我看到的潜在问题:
POSTS.publish_date
a DATETIME data type? POSTS.publish_date
是DATETIME数据类型吗? Verify that MySQL expects dates in that format. 验证MySQL是否期望该格式的日期。 You might be better off using MySQL's date functions to compose them.
使用MySQL的日期函数来组合它们可能会更好。
First, offload everything you can to MySQL. 首先,将所有内容卸载到MySQL。 The less date math you have to do the better.
日期数学越少,您要做的越好。
Second, Look at what your actual created code looks like. 其次,查看您实际创建的代码是什么样的。 Change this
改变这个
$q3 = $this->db->query("SELECT *
FROM posts
WHERE publish_date BETWEEN '$then' AND '$now'");
to this 对此
$sql = "SELECT *
FROM posts
WHERE publish_date BETWEEN '$then' AND '$now'");
print "EXECUTING: $sql\n";
$q3 = $this->db->query( $sql );
You're assuming that the SQL you are generating is valid, and it might not be. 您假设正在生成的SQL是有效的,但可能不是。 This is very common when you're using one language to generate code in another.
当您使用一种语言生成另一种语言的代码时,这很常见。 Always
print
to verify your assumptions. 始终
print
以验证您的假设。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.