PHP脚本中的MySQL语法错误

时间:2013-10-07 16:33:52

标签: php mysql sql

我在MySQL中有一个查询工作正常,但是当我将查询复制到我的PHP文件中时,它会给我一个语法错误:**意外“)week_ending **我错过了什么?

MySQL的:

  

'SELECT COUNT(*)为countregion,DATE_FORMAT(NOW(),'%​​d%b%y')为week_ending FROM stores.stats WHERE {{ 1}}> DATE_ADD(DATE(NOW()),INTERVAL -1 WEEK)和date< DATE(NOW())GROUP BY date,DATE(NOW())';

PHP:

  

$ stmt = DB :: query(数据库:: SELECT,'SELECT COUNT(*)为regioncount,DATE_FORMAT(NOW(),'%​​d%b%y') ,region FROM stores.stats WHERE week_ending> DATE_ADD(DATE(NOW()),INTERVAL -1 WEEK)和date< DATE(NOW())GROUP BY { {1}},DATE(NOW())';

2 个答案:

答案 0 :(得分:4)

SQL中间有几个单引号会过早地终止您的请求。你只需要逃避这附近的报价:

DATE_FORMAT(NOW(),'%d %b %y'),

像这样:

DATE_FORMAT(NOW(),\'%d %b %y\'),

答案 1 :(得分:2)

除了不转义包含的引号外,您还没有关闭方法调用。

$stmt = DB::query(
    Database::SELECT,
    'SELECT COUNT(*) as count,region, DATE_FORMAT(NOW(),\'%d %b %y\'), as week_ending FROM stores.stats WHERE date > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK) AND date < DATE(NOW()) GROUP BY region, DATE(NOW())'
);