我正在尝试创建一个查询,从我的数据库中提取有关卖家的信息,但前提是他们的商店在过去 3 天内已上线。我能想到的计算查询日期的最简单方法是使用 new DateTime() 对象。当我输出代码来测试它时,它是 MySQL 用来查询的正确字符串,但每当我尝试绑定(bind)变量时,都会收到错误。我正在使用 Zend_Db 来查询(PDO 适配器)
行动:
public function indexAction()
{
$dateMod = new DateTime();
$dateMod->modify('-2 days');
$dateMod->format('Y-m-d H:i:s');
// get sellers initialized in last 3 days
$sellerTable = new Application_Model_DbTable_Sellers();
$select = $sellerTable->select()->setIntegrityCheck(false);
$select->from(array('s' => 'seller'),array('sellerID', 'businessName'));
// select firstName, lastName, picture from user table, and businessName and sellerID from seller table.
$select->join(array('u' => 'user'), 's.userID = u.userID', array('firstName', 'lastName', 'picture'));
$select->where('s.active = 1 AND s.contentApproval = 1 AND s.paymentApproval = 1 AND s.featured = 1');
$select->where('s.launchDate > ?', $dateMod);
$select->order('s.launchDate DESC');
$newSellers = $sellerTable->fetchAll($select);
当我将 $dateMod
分配给 View 时,它会输出正确的 Y-m-d H:i:s
格式。但是当我将其插入查询时,出现以下错误:
Message: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ORDER BY `b`.`launchDate` DESC' at line 2
如果我以 mysql 时间戳格式将值硬编码到 dateMod 中,则查询工作正常。如何仅访问 DateTime 对象中时间戳的字符串值? getTimestamp
返回 unix 格式的时间戳,即使在指定格式之后也是如此。
最佳答案
format()
函数返回格式化的日期,因此您需要将其分配给一个变量以便在查询中使用:
$dateFormatted = $dateMod->format('Y-m-d H:i:s');
$select->where('s.launchDate > ?', $dateFormatted);
关于zend-framework - 在mysql查询中使用php DateTime对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10489386/